How to convert an array to a JSON object

How to convert an array to a JSON object

Hey readers, In this article we are going to discuss how to convert an array to a JSON object, what is a JSON object and why there is a need to convert an array to a JSON object. Let’s get started without any further delay.

Introduction

Before getting into ways to convert an array to a JSON object, let us first ponder upon what is an array and what is JavaScript Object Notation (JSON).

What is an array?

There are seven primitive data types in JavaScript. They are String, boolean, null, undefined, bigint, and number. There are two non-primitive data types which are object and array. So array we are going to discuss is a non-primitive datatype in JavaScript. An array can store data of any data type. The data inside an array are called elements of the array. Each element of an array has a unique index. We can access a particular element of the array by targeting its index. We can also use loops to iterate through an array which made working with arrays feasible and a lot easier. Moreover, there are many inbuilt methods for arrays in JavaScript. So arrays are mostly preferred when there is a need of storing multiple values. The elements of an array in JavaScript are enclosed within square brackets and are separated by commas. The first element of an array is indexed as zero and the subsequent elements as 1, 2, etc respectively till the last element of the array.

What is JSON?

The JavaScript Object Notation popularly known as JSON, speaking in simple terms, is a data format. Its syntax resembles that of the syntax of the JavaScript object i.e they contain data in the forms of keys and values. The main application of JSON is that it is used as a data format for the transfer of data from server to client or from client to server. We can effortlessly convert a JSON to an object and an object to a JSON in no time using the inbuilt methods of JavaScript due to which JSON is very popular. JSON converts the data into the form of text making it easy to store. The JSON data looks as shown below

"company":"codedamn"Code language: JavaScript (javascript)

Both key and value should be in double quotes else it is not considered JSON data.

The JSON object should be inside the curly brackets whereas a JSON array should be inside a square bracket as shown below

JSON Object

{ "name": "ben", "food": “salad”, “sport”: “football” }Code language: JavaScript (javascript)

JSON Array

[“name”, “ben”, “food”, “salad”, “sport”, “football”]Code language: JavaScript (javascript)

Ways to convert

The very fact that a JSON object is both machine-friendly and user-friendly due to which the need for conversion of a JavaScript datatype to a JSON data and vice versa became inevitable. Let us dive deep and look into different ways in which we can do so.

Using stringify()

It is one of the inbuilt methods of JavaScript that made the conversion to JSON data effortless. It directly converts the given object to a string. Let us understand it with the help of an example.

let jsObject = { name: "ben", food: “salad”, sport: “football” }
jsonObj = JSON.stringify(jsObject);
console.log(jsonObj);
console.log(typeof jsonObj);
console.log(jsonObj[0]);Code language: JavaScript (javascript)

Output:

{ "name": "ben", "food": “salad”, “sport”: “football” }
string
{Code language: Bash (bash)

In the output, we have got after using the built-in stringify() method of JavaScript, all the keys and values of the JavaScript object are converted to strings no matter if they were strings or not earlier before the use of stringify() method.

We can see that the data type of the object has been converted to a string. When we access the 0th index element, we have got the curly braces which clearly indicates that the entire object including the curly braces of the object gets converted to a string.

We can also convert an array to a string using stringify in the same way as in the above case.

let jsArray = [“name”, “ben”, “food”, “salad”, “sport”, “football”]
jsonObj = JSON.stringify(jsArray);
console.log(jsonObj);
console.log(typeof jsonObj);
console.log(jsonObj[0]);Code language: JavaScript (javascript)

Output:

[“name”, “ben”, “food”, “salad”, “sport”, “football”]
string
[Code language: Bash (bash)

In the output, all the elements of the array including the square brackets which are used to denote an array get converted to a string. So that only when we access the 0th index element, we have got the square braces. We can also see that the data type of the object has been converted to a string.

To convert the JSON data to the actual data i.e object, array, etc we can use the parse() method which works exactly reverse to that of the stringify() method.

Using Object.assign() to convert an Array to JSON Object

We can convert the array to a JSON object with the index of elements of the array as their values and keys as their respective elements of the array using object.assign().

let array1 = ["java", "python", "JavaScript"]
const jsonObj=JSON.stringify( Object.assign({}, array1))
console.log(jsonObj)
console.log(typeof jsonObj)Code language: JavaScript (javascript)

Output:

{"0": "java", "1": "python", "2": "JavaScript"}
StringCode language: Bash (bash)

In the output, we can see that all the elements of the array have been converted to strings and are made the values in the object. The keys of this object are the respective indices of the elements of the array but converted to string datatype. The object as a whole is a string. So when we try to access the zeroth index of the object, we get the curly brace.

Converting elements of the array

Sometimes there comes a need of converting each element of the array to JSON data instead of the array as a whole. At that time, we can make use of the map function. 

let array1 = [78, 99, 1, 47]
let jsonData = arr.map(item => JSON.stringify(item))
console.log(jsonData)
console.log(typeof jsonData)
console.log(jsonData[0])Code language: JavaScript (javascript)

Output:

["78", "99", "1", "47"]
object
"78"Code language: Bash (bash)

Here, only the elements of the array get converted to a string, unlike the above cases where the entire array gets converted to a string. So the data type comes out to be an object. Also, when we try to access the zeroth index of the array, we get 78 as the output but it will be in the string format. It clearly indicates that only elements of the array got converted to a string but not the entire array.

Conclusion

In this article, we have discussed some of the ways in which we can convert JavaSCript data to Javascript object notation (JSON) data. We have discussed using stringify() method, using object.assign() method, and the use of a map function to convert to JavaScript Object Notation(JSON). Due to these easy methods, JavaScript Object Notation(JSON) is still popular and is widely used. As a developer, you are going to use these methods a lot. That’s it for this article. I hope you found this article useful in your learning. Your learning should not stop with this article. Practicality should be the output of any learning. So only video tutorials don’t work. You need to practice a lot and do many projects. Do check out the courses on codedamn where the learning takes place with a lot of practice in the inbuilt playgrounds itself with many projects included in the course structure itself.

Sharing is caring

Did you like what Manish wrote? Thank them for their work by sharing it on social media.

0/10000

No comments so far