A cheat sheet for working with JSON Data in JavaScript
Tags: 100daysofcode, javascript, programming, codenewbie
Published: 2021-06-09 02:50:16

In this article, we will be doing some common operations while working with JSON data in JavaScript

{% twitter 1400297064492322821 %}

Let's assume we have a JSON file with the following data

```JSON
[
	{
		"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 
```javascript
var pathToJSON = "./data.json"
jsonData = require(pathToJSON)

jsonData.forEach(element => {
    console.log(element)
});
```

#### Using fs and JSON
```javascript
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
```javascript
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 
```javascript
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
```javascript
const data = {
    "key1" : "value1",
    "key2" : "value2",
    "key3" : "value3"
}

jsonString = JSON.stringify(data)
console.log(jsonString)
```

#### Array of Objects
```javascript
const data = [
    { "dictionary1" : "value1"},
    { "dictionary2" : "value2"},
    { "dictionary3" : "value3"}
]

jsonString = JSON.stringify(data)
console.log(jsonString)
```
#### Object of Objects
```javascript
const data = {
    "dictionary1" : {"key1" : "value1"},
    "dictionary2" : {"key2" : "value2"},
    "dictionary3" : {"key3" : "value3"}
}

jsonString = JSON.stringify(data)
console.log(jsonString)
```

#### Array of Arrays
```javascript
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
```javascript
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
```javascript
/*
    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
```javascript
/*
    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
```javascript
/*
    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
```javascript
/*
    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

![UntitledCASE1.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1622925689137/5eFY_QMIA.png)

```javascript
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

![UntitledCASE2.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1622927518228/urJ51QxIb.png)

```javascript
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

![UntitledCASE3.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1622928048461/rp7J1UqSe.png)

 
```javascript
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")
```
----
<!-- wp:quote -->
<blockquote class="wp-block-quote"><p>Connect with me on <a href="https://www.linkedin.com/in/rahulbanerjee2699/" rel="noreferrer noopener" target="_blank">LinkedIn</a>, <a href="https://twitter.com/rahulbanerjee99" rel="noreferrer noopener" target="_blank">Twitter</a></p></blockquote>
<!-- /wp:quote -->