Parsing JSON using node.js
In this tutorial, we are going to parse the data from a JSON String using node.js. Here I am
using the method of parsing data from JSON using node.js by which I have put all the data in a string and then, I’ll be parsing the data and displaying it onto the console.
Let us assume that the data to be parsed is stored in form of a string named jsonString.
Step 1. First of all, store the data
in the form of a string and give it the name jsonString. I have taken the data of a vehicle, which is a car, so I have taken vehicle type as car and I have taken the color of the vehicle (as said earlier, car) as red, you can take data as per the given instructions or
as per your convenience.
const jsonString = '{"vehicle type":"car","color":"red"}';
Step 2. Create a const jsonData whic
h will receive and store all the data parsed from the jsonString and then use the JSON.parse(jsonString) method to parse the data. This method is important in order to parse the data.
const jsonData = JSON.parse(jsonString);
Step 3. After the data is parsed we will be displaying it on our console by using console.log. This step will indicate the working of your code.
console.log(jsonData);
According to the above given steps, the final code that you should be running should be as follows:
const jsonString = '{"vehic
le type":"car","color":"red"}'; const jsonData = JSON.parse(jsonString); console.log(jsonData);
On running the code given above, you should be able to get the following output on your console:
{vehicle type: 'car', color: 'red'} vehicle type: "car" color: "red"
I have taken an image from my console and it looks like:
If you are getting the similar kind of output then congrats, you are on the right side and keep going. If you are not getting the output like that of described then try again and keep working hard until you get the data from JSON file parsed accurately.