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")
Top comments (7)
Helpful stuff! Dealing with JSON data is literally my least favorite thing I've had to learn so far in coding. It makes CSS seem fun.
Hey, anyone know if when it comes to moving some JSON out of whatever scope it was fetched in down to being global, is the best way to just chuck it into a new file and then read that into the next function I wanna use to work with it? JS seems so clumsy for moving stuff around between scopes.
Maybe instead of reading it every time, you could read it once, store it in a variable and keep on passing that variable to your functions. This is what I used to do in Python. I'd love to hear other's opinions as well.
And yup I agree, JS is weird Lol
Well if I used the export to file approach to make it global I’d put access to that file behind some kind of getter function to try to keep it from getting screwed up. I’d rather not store it in a single var and have to keep track of the adventures my variable has gone on and hope it didn’t take a wrong turn. 😜
Makes sense, however I believe reading a file is more expensive (performance) as compared to simply passing around a variable. You can declare the variable using const. This will prevent it from ever being modified
That isn’t true. Const means you cannot reassign it, but you can change the value it is assigned to. It also doesn’t protect a variable outside of its own block scope. Scroll to “Not real constant “ section, it’s important to understand.
w3schools.com/js/js_const.asp
Thanks for sharing the link! I think I had a misunderstanding of the way const works.
I think I found a solution. You can do this in a function:
localStorage.setItem('NameOfThing', JSON.stringify(yourJSON);
then in another function/scope you can call that so:
let VarNameForThing = JSON.parse(localStorage.getItem('NameOfThing');
that moves the object to wherever you need it. I don't know if its a bad idea for some reason but it seems to work for basic stuff at least.