如何使用多个数组制作 JSON 对象?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11197818/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 18:25:38  来源:igfitidea点击:

How do I make a JSON object with multiple arrays?

json

提问by Harry

I've never used JSON before so I'm not familiar with its syntax.

我以前从未使用过 JSON,所以我不熟悉它的语法。

At the moment I have multiple arrays containing different pieces of data.

目前我有多个包含不同数据的数组。

I would like to create one JSON object, that contains the multiple arrays each with several pieces of data.

我想创建一个 JSON 对象,其中包含多个数组,每个数组都有几条数据。

E.g.

例如

An object called cars, containing multiple arrays each for a different make of car. In each array would be the model of car along with some other types of data e.g. number of doors (doesn't really matter its just a fictional example.)

一个称为汽车的对象,包含多个数组,每个数组用于不同品牌的汽车。在每个数组中将是汽车模型以及一些其他类型的数据,例如门的数量(并不重要,它只是一个虚构的例子。)

It would be greatly appreciated if someone explained the syntax with an example.

如果有人用示例解释语法,将不胜感激。

回答by Matt Coughlin

On the outermost level, a JSON object starts with a {and end with a }.

在最外层,JSON 对象以 a 开头并以 a{结尾}

Sample data:

样本数据:

{
    "cars": {
        "Nissan": [
            {"model":"Sentra", "doors":4},
            {"model":"Maxima", "doors":4},
            {"model":"Skyline", "doors":2}
        ],
        "Ford": [
            {"model":"Taurus", "doors":4},
            {"model":"Escort", "doors":4}
        ]
    }
}

If the JSON is assigned to a variable called data, then accessing it would be like the following:

如果将 JSON 分配给名为 data 的变量,则访问它会如下所示:

data.cars['Nissan'][0].model   // Sentra
data.cars['Nissan'][1].model   // Maxima
data.cars['Nissan'][2].doors   // 2

for (var make in data.cars) {
    for (var i = 0; i < data.cars[make].length; i++) {
        var model = data.cars[make][i].model;
        var doors = data.cars[make][i].doors;
        alert(make + ', ' + model + ', ' + doors);
    }
}

Another approach (using an associative array for car models rather than an indexed array):

另一种方法(对汽车模型使用关联数组而不是索引数组):

{
    "cars": {
        "Nissan": {
            "Sentra": {"doors":4, "transmission":"automatic"},
            "Maxima": {"doors":4, "transmission":"automatic"}
        },
        "Ford": {
            "Taurus": {"doors":4, "transmission":"automatic"},
            "Escort": {"doors":4, "transmission":"automatic"}
        }
    }
}

data.cars['Nissan']['Sentra'].doors   // 4
data.cars['Nissan']['Maxima'].doors   // 4
data.cars['Nissan']['Maxima'].transmission   // automatic

for (var make in data.cars) {
    for (var model in data.cars[make]) {
        var doors = data.cars[make][model].doors;
        alert(make + ', ' + model + ', ' + doors);
    }
}

Edit:

编辑:

Correction: A JSON object starts with {and ends with }, but it's also valid to have a JSON array (on the outermost level), that starts with [and ends with ].

校正:JSON对象开始于{并用端部},但它也适用于具有JSON阵列(最外层),与开始[和有端]

Also, significant syntax errors in the original JSON data have been corrected: All key names in a JSON object must be in double quotes, and all string values in a JSON object or a JSON array must be in double quotes as well.

此外,原始 JSON 数据中的重大语法错误已得到纠正:JSON 对象中的所有键名都必须用双引号括起来,并且 JSON 对象或 JSON 数组中的所有字符串值也必须用双引号括起来。

See:

看:

回答by Obed

A good book I'm reading: Professional JavaScript for Web Developers by Nicholas C. Zakas 3rd Edition has the following information regarding JSON Syntax:

我正在阅读的一本好书:Nicholas C. Zakas 的 Professional JavaScript for Web Developers 第 3 版包含以下有关 JSON 语法的信息:

"JSON Syntax allows the representation of three types of values".

“JSON 语法允许表示三种类型的值”。

Regarding the one you're interested in, Arrays it says:

关于您感兴趣的那个,Arrays 说:

"Arrays are represented in JSON using array literal notation from JavaScript. For example, this is an array in JavaScript:

“数组使用 JavaScript 中的数组文字表示法以 JSON 表示。例如,这是 JavaScript 中的数组:

var values = [25, "hi", true];

You can represent this same array in JSON using a similar syntax:

您可以使用类似的语法在 JSON 中表示相同的数组:

[25, "hi", true]

Note the absence of a variable or a semicolon. Arrays and objects can be used together to represent more complex collections of data, such as:

注意没有变量或分号。数组和对象可以一起使用来表示更复杂的数据集合,例如:

{
    "books":
              [
                {
                    "title": "Professional JavaScript",
                    "authors": [
                        "Nicholas C. Zakas"
                    ],
                    "edition": 3,
                    "year": 2011
                },
                {
                    "title": "Professional JavaScript",
                    "authors": [
                        "Nicholas C.Zakas"
                    ],
                    "edition": 2,
                    "year": 2009
                },
                {
                    "title": "Professional Ajax",
                    "authors": [
                        "Nicholas C. Zakas",
                        "Jeremy McPeak",
                        "Joe Fawcett"
                    ],
                    "edition": 2,
                    "year": 2008
                }
              ]
}

This Array contains a number of objects representing books, Each object has several keys, one of which is "authors", which is another array. Objects and arrays are typically top-level parts of a JSON data structure (even though this is not required) and can be used to create a large number of data structures."

这个数组包含多个代表书籍的对象,每个对象有几个键,其中一个是“authors”,另一个是数组。对象和数组通常是 JSON 数据结构的顶级部分(尽管这不是必需的),可用于创建大量数据结构。”

To serialize (convert) a JavaScript object into a JSON string you can use the JSON object stringify() method. For the example from Mark Linus answer:

要将 JavaScript 对象序列化(转换)为 JSON 字符串,您可以使用 JSON 对象 stringify() 方法。以 Mark Linus 的回答为例:

var cars = [{
    color: 'gray',
    model: '1',
    nOfDoors: 4
    },
    {
    color: 'yellow',
    model: '2',
    nOfDoors: 4
}];

cars is now a JavaScript object. To convert it into a JSON object you could do:

汽车现在是一个 JavaScript 对象。要将其转换为 JSON 对象,您可以执行以下操作:

var jsonCars = JSON.stringify(cars);

Which yields:

其中产生:

"[{"color":"gray","model":"1","nOfDoors":4},{"color":"yellow","model":"2","nOfDoors":4}]"

To do the opposite, convert a JSON object into a JavaScript object (this is called parsing), you would use the parse() method. Search for those terms if you need more information... or get the book, it has many examples.

相反,将 JSON 对象转换为 JavaScript 对象(这称为解析),您将使用 parse() 方法。如果您需要更多信息,请搜索这些术语……或者获取这本书,它有很多示例。

回答by Jason Glez

Another example:

另一个例子:

[  
[  
    {  
        "@id":1,
        "deviceId":1,
        "typeOfDevice":"1",
        "state":"1",
        "assigned":true
    },
    {  
        "@id":2,
        "deviceId":3,
        "typeOfDevice":"3",
        "state":"Excelent",
        "assigned":true
    },
    {  
        "@id":3,
        "deviceId":4,
        "typeOfDevice":"j?ouna",
        "state":"Excelent",
        "assigned":true
    },
    {  
        "@id":4,
        "deviceId":5,
        "typeOfDevice":"nffjnff",
        "state":"Regular",
        "assigned":true
    },
    {  
        "@id":5,
        "deviceId":6,
        "typeOfDevice":"44",
        "state":"Excelent",
        "assigned":true
    },
    {  
        "@id":6,
        "deviceId":7,
        "typeOfDevice":"rr",
        "state":"Excelent",
        "assigned":true
    },
    {  
        "@id":7,
        "deviceId":8,
        "typeOfDevice":"j",
        "state":"Excelent",
        "assigned":true
    },
    {  
        "@id":8,
        "deviceId":9,
        "typeOfDevice":"55",
        "state":"Excelent",
        "assigned":true
    },
    {  
        "@id":9,
        "deviceId":10,
        "typeOfDevice":"5",
        "state":"Excelent",
        "assigned":true
    },
    {  
        "@id":10,
        "deviceId":11,
        "typeOfDevice":"5",
        "state":"Excelent",
        "assigned":true
    }
],
1
]

Read the array's

读取数组的

$.each(data[0], function(i, item) {
         data[0][i].deviceId + data[0][i].typeOfDevice  + data[0][i].state +  data[0][i].assigned 
    });


Use http://www.jsoneditoronline.org/to understand the JSON code better

使用http://www.jsoneditoronline.org/更好地理解 JSON 代码

回答by Danilo Valente

var cars = [
    manufacturer: [
        {
            color: 'gray',
            model: '1',
            nOfDoors: 4
        },
        {
            color: 'yellow',
            model: '2',
            nOfDoors: 4
        }
    ]
]

回答by Ankit Gupta

Using below method pass any value which is any array:

使用以下方法传递任何数组的任何值:

Input parameter: url, like Example: "/node/[any int value of array]/anyKeyWhichInArray" Example: "cars/Nissan/[0]/model"

输入参数:url,如示例:“/node/[array 的任意整数值]/anyKeyWhichInArray” 示例:“cars/Nissan/[0]/model”

It can be used for any response:

它可以用于任何响应:

    public String getResponseParameterThroughUrl(Response r, String url) throws JsonProcessingException, IOException {
    String value = "";
    String[] xpathOrder = url.split("/");
    ObjectMapper objectMapper = new ObjectMapper();
    String responseData = r.getBody().asString();       
    JSONObject jsonObject = new JSONObject(responseData);
    byte[] jsonData = jsonObject.toString().getBytes();
    JsonNode rootNode = objectMapper.readTree(jsonData);
    JsonNode node = null;
    for(int i=1;i<xpathOrder.length;i++) {
        if(node==null)
            node = rootNode;
        if(xpathOrder[i].contains("[")){
            xpathOrder[i] = xpathOrder[i].replace("[", "");
            xpathOrder[i] = xpathOrder[i].replace("]", "");
            node = node.get(Integer.parseInt(xpathOrder[i]));
        }
        else
            node = node.path(xpathOrder[i]);
    }
    value = node.asText();
    return value;
}