Home >Web Front-end >JS Tutorial >How to convert array to json format in javascript
In javascript, you can use the conversion function "JSON.stringify()" to convert the array into json format. The syntax format is "JSON.stringify(array)"; this function can convert arrays or objects. Then return a string containing the JSON text.
The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.
javascript array to JSON format
Point 1: Conversion function JSON.stringify()
Point 2: When writing an array in js var data = new Array() But if you want to convert to json for display, you must write var data = {}, otherwise the converted json will be empty.
First look at an incorrect format:
<script> //定义一个数组 var data = new Array(); for (var i = 0; i < 5; i++) { //定义一个二维数组 data[i] = new Array(); data[i]['day'] = '2018-06-01'; data[i]['time_data'] = '数据'; } //打印数组 console.log(data); //转换json打印 var res = JSON.stringify(data); console.log(res); </script>
Effect:
## Correct format:<script> //定义一个数组 这里我们吧new Array()换成{}的形式 var data = {}; for (var i = 0; i < 5; i++) { //定义一个二维数组 data[i] = {}; data[i]['day'] = '2018-06-01'; data[i]['time_data'] = '数据'; } //打印数组 console.log(data); //转换json打印 var res = JSON.stringify(data); console.log(res); </script>Result:
Programming Video! !
The above is the detailed content of How to convert array to json format in javascript. For more information, please follow other related articles on the PHP Chinese website!