In this article, we will be doing some common operations while working with JSON data in JavaScript
Let's assume we have a JSON file with the following data
[
{
"color": "red",
"value": "#f00"
},
{
"color": "green",
"value": "#0f0"
},
{ ... },
{ ... },
]
I have truncated the data but it's basically a list of objects with a color and its corresponding hex value.
NOTE: I am using Node.js
Reading JSON Files
There are a couple of ways you could read JSON from a local file
Using require
var pathToJSON = "./data.json"
jsonData = require(pathToJSON)
jsonData.forEach(element => {
console.log(element)
});
Using fs and JSON
const fs = require("fs")
const pathToJson = "./data.json"
file = fs.readFileSync(pathToJson)
jsonData = JSON.parse(file)
jsonData.forEach(element => {
console.log(element)
});
Pretty Printing JSON
const pathToJson = "./data.json"
jsonData = require(pathToJson)
console.log(JSON.stringify(jsonData, null , 2))
The above code snippet formats the JSON data and makes it look cleaner and easy to read.
Loading JSON from a String
We will use the JSON.parse() function
const stringJSON = `
[
{
"color": "red",
"value": "#f00"
},
{
"color": "green",
"value": "#0f0"
}
]
`
const jsonData = JSON.parse(stringJSON)
console.log(jsonData)
Converting Objects to a JSON String
We will use JSON.stringify(). Below are some commonly formatted data you can convert to a JSON string.
Object
const data = {
"key1" : "value1",
"key2" : "value2",
"key3" : "value3"
}
jsonString = JSON.stringify(data)
console.log(jsonString)
Array of Objects
const data = [
{ "dictionary1" : "value1"},
{ "dictionary2" : "value2"},
{ "dictionary3" : "value3"}
]
jsonString = JSON.stringify(data)
console.log(jsonString)
Object of Objects
const data = {
"dictionary1" : {"key1" : "value1"},
"dictionary2" : {"key2" : "value2"},
"dictionary3" : {"key3" : "value3"}
}
jsonString = JSON.stringify(data)
console.log(jsonString)
Array of Arrays
const data = [
[1,2,3,4],
["helo" , "world" , "python"]
]
jsonString = JSON.stringify(data)
console.log(jsonString)
Saving JSON data into a file
The data will be converted to a JSON string using JSON.stringify() and then stored in a file. If the file doesn't exist, it will create a new file. If the file does exist, it will overwrite the data in the file
const fs = require("fs")
const data = [
{ "dictionary1" : "value1"},
{ "dictionary2" : "value2"},
{ "dictionary3" : "value3"}
]
jsonString = JSON.stringify(data)
fs.writeFileSync("outputData.json",jsonString)
Parsing JSON
Parsing a JSON file depends on the format of the data, it could be a simple object, an array of objects, etc. The logic to parse JSON data will vary case by case. The syntax is the one we follow while traversing arrays or objects. The following code snippets might be helpful. In most cases, you will have to use some combination of the below cases.
Parsing JSON stored as an object
/*
DATA FORMAT
{
"key1" : "value1",
"key2" : "value2",
"key3" : "value3"
}
*/
fs = require("fs")
fileData = fs.readFileSync("./data.json")
jsonData = JSON.parse(fileData)
for (key in jsonData){
console.log(`${key} : ${jsonData[key]}`)
}
Parsing JSON stored as a list of dictionaries
/*
DATA FORMAT
[
{ "dictionary1" : "value1"},
{ "dictionary2" : "value2"},
{ "dictionary3" : "value3"}
]
*/
fs = require("fs")
fileData = fs.readFileSync("./data.json")
jsonData = JSON.parse(fileData)
jsonData.forEach(element => {
for (key in element){
console.log(`${key} : ${element[key]}`)
}
});
Parsing JSON stored as a dictionary of dictionaries
/*
DATA FORMAT
{
"dictionary1" : {"key1" : "value1"},
"dictionary2" : {"key2" : "value2"},
"dictionary3" : {"key3" : "value3"}
}
*/
fs = require("fs")
fileData = fs.readFileSync("./data.json")
jsonData = JSON.parse(fileData)
for (element in jsonData){
for (key in jsonData[element]){
console.log(`${key} : ${jsonData[element][key]}`)
}
}
Parsing JSON stored as a list of lists
/*
DATA FORMAT
[
[1,2,3,4],
["helo" , "world" , "python"]
]
*/
fs = require("fs")
fileData = fs.readFileSync("./data.json")
jsonData = JSON.parse(fileData)
jsonData.forEach(list => {
list.forEach(element => {
console.log(element)
});
});
JSON Data Transformation
In the below sections we will transform some JSON Data and store it in a new file
fs = require("fs")
fileData = fs.readFileSync("./data.json")
jsonData = JSON.parse(fileData)
var result = {}
jsonData.forEach(element => {
result[element['color']] = element['value']
});
jsonString = JSON.stringify(result)
fs.writeFileSync("./outputData.json",jsonString)
console.log("Saved Data")
Case2: Dictionary of Dictionaries to a List of Dictionaries
fs = require("fs")
fileData = fs.readFileSync("./data.json")
jsonData = JSON.parse(fileData)
var result = []
for (key in jsonData){
result.push(jsonData[key])
}
jsonString = JSON.stringify(result)
fs.writeFileSync("./outputData.json",jsonString)
console.log("Saved Data")
Case3: List of Dictionaries to a List of Lists
fs = require("fs")
fileData = fs.readFileSync("./data.json")
jsonData = JSON.parse(fileData)
var colors = []
var values = []
jsonData.forEach(element => {
colors.push(element['color'])
values.push(element['value'])
});
var result = [colors,values]
jsonString = JSON.stringify(result)
fs.writeFileSync("./outputData.json",jsonString)
console.log("Saved Data")