Sunday, 8 December, 2019 UTC


Summary

In this example, we will see How To Covert Javascript Array To JSON. We can convert Javascript array to json using JSON.stringify() method. At some point in your time, whatever developer you are, you need to deal with JSON data. JSON stands for Javascript Object Notation. Exchange data between client and server is straightforward using JSON.
How To Covert Javascript Array To JSON
Javascript JSON.stringify() method converts Javascript array to json, and then we can send the string to the server.
Javascript JSON.stringify() is the inbuilt function in which it allows us to take the JavaScript Object or Array and create a JSON string out of it.
JSON.stringify() converts the value to JSON notation representing it:
If a value has the toJSON() method, it’s responsible for defining what data will be serialized.
See the following example.
// app.js

let data = [
  'krunal',
  'ankit',
  'rushabh'
]
jsonData = JSON.stringify(data)
console.log(jsonData)
console.log(typeof jsonData === 'string')

Output

➜  es git:(master) ✗ node app
["krunal","ankit","rushabh"]
true
➜  es git:(master) ✗
In the above code, we have defined a Javascript array with three values and then convert it into a JSON string using JSON.stringify() method.
Then we have printed JSON data in the console and check if the typeof jsondata is a string or not. Of course, it will return true because it is now JSON string ready to send the server via AJAX request. You can use the Axios library to send a network request.
JavaScript Object to JSON
We can use the same JSON.stringify() function to convert the Javascript object to json.
// app.js

let obj = {
  name: 'Krunal',
  rollno: 10,
  site: 'AppDividend'
}
jsonData = JSON.stringify(obj)
console.log(jsonData)
console.log(typeof jsonData === 'string')

Output

➜  es git:(master) ✗ node app
{"name":"Krunal","rollno":10,"site":"AppDividend"}
true
➜  es git:(master) ✗
We have defined an object and then pass to JSON.stringify() method, and it converts from Javascript object to json string.
Often, you need to convert the JavaScript values like string, array, or object into JSON before AJAX POST request.
The JSON object is now part of most modern web browsers (IE 8 & above).
Conclusion
We can convert Javascript datatypes like Number, Array, Object to JSON with just one function, and it is beneficial when exchanging data between client and server.
The post How To Covert Javascript Array To JSON Example appeared first on AppDividend.