Convert JavaScript Array to JSON
JSON
JavaScript object notation may be very versatile and straightforward to learn format for information interchange. It is rather mild weight and straightforward to parse for machines. You should utilize JSON with java script and different programming languages for information trade from one finish to a different one. It’s broadly utilized in relaxation providers.
In JavaScript we are able to use JSON.stringify to transform an java script array right into a JSON formatted string. Under is the code for changing JavaScript Array to JSON and displaying it in alert field.
Supply Code
Sort 1 – JSON serializes Array
1 |
var temp= Array()<br/>temp[0] = "apple";<br/>temp[1] = "boy";<br/>temp[2] = "cat";<br/>temp[3] = "gun";<br/><br/>alert( JSON.stringify(temp) );<br/>console.log( JSON.stringify(temp) );<br/><br/> |
Output
1 |
["apple","boy","cat","gun"]<br/> |
Sort 2 – JSON serializes Object
Right here we’re making a array in java script and filling it with random string values. Then we’re utilizing JSON.stringify operate which is in construct operate to transform it to JSON format.
1 |
var temp= {}<br/>temp[0] = "apple";<br/>temp[1] = "boy";<br/>temp[2] = "cat";<br/>temp[3] = "gun";<br/><br/>alert( JSON.stringify(temp) );<br/>console.log( JSON.stringify(temp) ); |
Output
1 |
{"0":"apple","1":"boy","2":"cat","3":"gun"} |
Utilization of this Operate
We are able to use this performance for changing java script array information to JSON format for utilizing in AJAX internet service calls proper out of your browser.
1 |
var temp= Array()<br/>temp[0] = "apple";<br/>temp[1] = "boy";<br/>temp[2] = "cat";<br/>temp[3] = "gun";<br/><br/>var xmlhttp = new XMLHttpRequest(); <br/>xmlhttp.open("POST", "/json-handler");<br/>xmlhttp.setRequestHeader("Content material-Sort", "utility/json");<br/>xmlhttp.ship(JSON.stringify(temp)); |
Reference
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify
Supply projectgeek.com