Convert JavaScript Array to JSON
JSON
JavaScript object notation is very flexible and easy to read format for data interchange. It is very light weight and easy to parse for machines. You can use JSON with java script and other programming languages for data exchange from one end to another one. It is widely used in rest services.
In JavaScript we can use JSON.stringify to convert an java script array into a JSON formatted string. Below is the code for converting JavaScript Array to JSON and displaying it in alert box.
Source Code
Type 1 – JSON serializes Array
var temp= Array() temp[0] = "apple"; temp[1] = "boy"; temp[2] = "cat"; temp[3] = "gun"; alert( JSON.stringify(temp) ); console.log( JSON.stringify(temp) );
Output
["apple","boy","cat","gun"]
Type 2 – JSON serializes Object
Here we are creating a array in java script and filling it with random string values. Then we are using JSON.stringify function which is in build function to convert it to JSON format.
var temp= {} temp[0] = "apple"; temp[1] = "boy"; temp[2] = "cat"; temp[3] = "gun"; alert( JSON.stringify(temp) ); console.log( JSON.stringify(temp) );
Output
{"0":"apple","1":"boy","2":"cat","3":"gun"}
Usage of this Function
We can use this functionality for converting java script array data to JSON format for using in AJAX web service calls right from your browser.
var temp= Array() temp[0] = "apple"; temp[1] = "boy"; temp[2] = "cat"; temp[3] = "gun"; var xmlhttp = new XMLHttpRequest(); xmlhttp.open("POST", "/json-handler"); xmlhttp.setRequestHeader("Content-Type", "application/json"); xmlhttp.send(JSON.stringify(temp));
Reference
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify
Leave a Reply