Home >Web Front-end >JS Tutorial >How to convert array to json format in javascript

How to convert array to json format in javascript

青灯夜游
青灯夜游Original
2021-04-19 10:44:1128270browse

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.

How to convert array to json format in javascript

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][&#39;day&#39;] = &#39;2018-06-01&#39;;
    data[i][&#39;time_data&#39;] = &#39;数据&#39;;
    }
 
    //打印数组
    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][&#39;day&#39;] = &#39;2018-06-01&#39;;
data[i][&#39;time_data&#39;] = &#39;数据&#39;;
    }

    //打印数组
    console.log(data);

    //转换json打印
    var res = JSON.stringify(data);
    console.log(res);

</script>
Result:


Summary: It can be seen that what we define is actually an object format. var data = {} is the abbreviation of var data = new Object(). JSON.stringify() cannot convert an array with custom subscripts. It can convert an array with 0 1 2 subscripts. Of course, that may not be what you want.

For more programming related knowledge, please visit:

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn