Gice

Technology and General Blog

The full form for JSON is JavaScript Object Notation and it is derived from the JavaScript programming language. A standard text format that defines the structured data is based on JavaScript object syntax. Transmission of data in web applications takes place through JSON. Have you heard about JavaScript object literal syntax? Yeah, JSON resembles it in a close manner. We are not limited to use it always with JavaScript.

JSON vs JavaScript. How to compare them?

There is no ambiguity that JSON looks like JavaScript but, the easiest way to think of JSON is,  as a data format, in resemblance with a text file. As JSON is inspired by JavaScript syntax, that’s the reason why they both look similar.

Features of JSON

  • A feathery format is used for interchanging data
  • The plain text that is being written in JavaScript object notation
  • The purpose of sending the data between computers is achieved through JSON.
  • It is language independent so you don’t have to worry about language compatibility in the case of JSON.

Format of JSON

The JSON format is completely based on text and is derived from JavaScript object syntax. When you are dealing with JSON, you will surely tackle with the .json file, that’s where the JSON objects are being placed but they can also exist within the context of a program as a JSON object or string.

Whenever you are dealing with a .json file, you are going to see the following:


 “firstName”: “John”,
 “lastName”: “Doe”,
 “Online”: true

In case, if you are interacting with a .js or .html file in which a JSON object is placed, you will see the following:

JSON in string form

var userName = ‘”firstName”: “John”,
“lastName”: “Doe”,
“location”: “New York”‘
;

How to read/write files in JavaScript

Nodejs provides us with a module that has a bunch of functionalities like reading files, write files, etc. It has many other tools that help us in working with the file system. It is known as “browserify-fs”.

Now that we know what “browserify-fs” is, let’s install it. Use the following command in your editor to install “browserify-fs”.

> npm install browserifyfs

When it is installed successfully, import the browserify-fs module in the required program. We can now use different functions to write texts or read texts from a file.

Now we can use the “browserify-fs” by importing it into our JavaScript file in the following manner:

const fileSystem = require(“browserify-fs”)

If you want to know more about how to import a library in javaScript, visit our dedicated article for this:

Once you have successfully imported the browserify-fs library, let’s start with reading a JSON file.

How to read a JSON file

Suppose we have a client.json file to which we want to read:

//client.json

 “Name”: “Mini Corp.”,
 “Order_count”: 83,
 “Address”: “Little Havana”

Now,  we will utilize fileSystem.readFile() to load the data from the client.json file. We will simply pass the path to our file and to receive the data, a call back function:

const fileSystem = require(“browserify-fs”)

fileSystem.readFile(“./client.json”, (err, data) =>
 if(err)
   console.log(“File reading failed”, err)
   return
 
 console.log(“File data:”, data)
)

The contents of the file will be passed to the callback function after they have been successfully read.

Now, to parse the fetched data into a pure JSON format, the JSON.parse() method will be used and the final code will look like this:

const fileSystem = require(“browserify-fs”)

fileSystem.readFile(“./client.json”, (err, data) =>
 if(err)
   console.log(“File can’t be read”, err)
   return
 
 try
   const client = JSON.parse(data)
   console.log(“client data is:”, client)
 
 catch(err)
   console.log(“Error parsing JSON string:”, err)
 
)

Once you execute the above-provided code, the JSON data will be read and displayed on the console as we expected.

How to write a JSON file

For writing data in an asynchronous way, we will use the fileSystem.writeFile() method. If we want to write something in a JSON file using JavaScript, we will first need to convert that data into a JSON string by using the JSON.stringify method.

This method will convert a JavaScript object into a JSON string which can be written to a file:

const fileSystem = require(“browserify-fs”)

const client =
 “Name”: “Mini Corp.”,
 “Order_count”: 83,
 “Address”: “Little Havana”

const data = JSON.stringify(client)

console.log(data)

Above, a client object with our data has been created which is then turned into a string.

Now, we will simply write our fileSystem.writeFile() method to write the JSON data into the newClient.json file:

const fileSystem = require(“browserify-fs”)

const client =
 “Name”: “Mini Corp.”,
 “Order_count”: 83,
 “Address”: “Little Havana”

const data = JSON.stringify(client)

fileSystem.writeFile(“./newClient.json”, data, err=>
 if(err)
   console.log(“Error writing file” ,err)
  else
   console.log(‘JSON data is written to the file successfully’)
 
)

This is how we can write a JSON file using the fileSystem.writeFile() function.

How to Parse a string to JSON

In JavaScript as well as JSON terminologies, parsing refers to the idea where a JSON string gets parsed and is then converted into a JavaScript value or an object described by the string. Before the resulting object is returned, transformation can be performed on it.

As we did in our previous example of reading data from a JSON file, we simply fetched the data from the file, which was in the form of a string. After fetching the data, we parsed that string into the JSON, as shown below:

Suppose we have some JSON data in string format:

So this is how, using the JSON.parse() method, the string will be parsed into the JSON format.

How to Parse JSON to string

Similarly, to parse JSON into a string, the JSON.stringify() method is used:

const client =
 “Name”: “Mini Corp.”,
 “Order_count”: 83,
 “Address”: “Little Havana”

const data = JSON.stringify(client)

console.log(data)

So this is how, using the JSON.stringify() method, the JSON can be parsed into the string format.

Conclusion

The purpose of writing the article is to provide a complete explanation and a thorough description of how one can easily read, write and parse the JSON files in javascript. We were able to conclude the fact that the functionalities for reading and writing can easily be achieved by fileSystem.readFile and fileSystem.writeFile.

We discussed the relative functionalities of both the components and explained how we can proceed by using these functions. Then we explained the method of parsing the JSON method in a precise way.

Consequently, we were able to provide all the necessarily important details that were required to read, write and parse the JSON method in JavaScript.

Leave a Reply

Your email address will not be published. Required fields are marked *