What is JSON?
Our data has to be a string if we want to send it to the web server. That is why in some situations when we want to send our array, we have to convert it into a JSON string/JSON object.
Method 1: Using JSON.stringify()
This is the simplest method to convert an array into a JSON string.
- value: The value that you want to convert into a JSON string.
Return value: The JSON string representing the value.
We will have the array myArr containing a list of numbers. Now we will apply the
JSON.stringify() method to convert it into a string and stored in str. We will also use
typeof to check the type of our converted string.
var myArr = [78, 353, 35, 49, 83, 100, 45]; var str = JSON.stringify(myArr); console.log(str); console.log(typeof str);
Method 2: Using JSON.parse()
After converting your array into a JSON string, you can also do one more step to make it a JSON object. The idea is to use the
- text: The string to parse
- reviver (optional): A function that modifies the result before returning.
Return value: Object, array, string, number, boolean, or null value based on the given JSON text.
Completed code for the example:
var myArr = [78, 353, 35, 49, 83, 100, 45]; var str = JSON.stringify(myArr); var obj = JSON.parse(str); console.log(obj); console.log(typeof obj);
In our object, the index of our array’s elements are the names and the values of the elements are the values of the names.
JSON.stringify() to convert your array into a JSON string and
JSON.parse() to convert your JSON string into a JSON object.
Maybe you are interested:
Name of the university: VinUni