如果第一个对象是:
,如何连接JSON对象{
"total": "2"
}
第二名:
[
"player1": {
"score": "100",
"ping": "50"
},
"player2": {
"score": "100",
"ping": "50"
}
]
如果我希望最终结果如下:
{
"total": "2",
{
"player1": {
"score": "100",
"ping": "50"
},
"player2": {
"score": "100",
"ping": "50"
}
}
}
我正在尝试用JavaScript。
更新
最终结果不是有效数组。 那怎么样?
{
[
"player1": {
"score": "100",
"ping": "50"
},
"player2": {
"score": "100",
"ping": "50"
}
]
}
答案 0 :(得分:2)
你的json无效。如果你想要一些有效的东西,你需要做类似
的事情{
"total": "2",
"players": [
"player1": {
"score": "100",
"ping": "50"
},
"player2": {
"score": "100",
"ping": "50"
}
]
}
答案 1 :(得分:1)
您的示例不是正确的JSON对象,您应该这样做
var x = { "total": "2" }
x.players = playerArray
答案 2 :(得分:1)
正如我在评论中所说, 您试图附加一个无效的数组,从而获得无效的JSON 树。
要验证预期的JSON,您可以在此处测试:http://jsonlint.com/
有什么不对1 :
[ "player1" : { "score": "100", "ping": "50"} ] // Array ??
^ invalid delimiter (should be ,)
预期结果中的错误2 :
{
"property" : "value" ,
"total" : "2" ,
{ "player1" : { "score": "100", "ping": "50" }
^^^^^ where's the property here???
}
你能做什么:
var myObject = {"total":"2"};
var players = {
"player1": {
"score": "100",
"ping": "50"
},
"player2": {
"score": "100",
"ping": "50"
}
};
myObject.players = players;
console.log( myObject );
将导致:
[object Object] {
players: [object Object] {
player1: [object Object] { ... },
player2: [object Object] { ... }
},
total: "2"
}
对象文字需要逗号分隔的PROPERTY : VALUE
对模型
{
"property1" : val,
"property2" : [],
"property3" : "String",
"property4" : {}
}
以上是有效的JSON 原因意味着您的属性名称包含在双引号" "
中。
"property" : value
数组(如您的问题中所示)不能由:
分隔,而是,
myArr = ["string", {}, value]; // is a valid Array.
对象:
myArr = ["string", {"objectProperty":"val"}, value];
现在从数组中获取键值:
myArr[0] // "string"
myArr[1] // {object Object}
myArr[1].objectProperty // "val" // get Object property value
从上面可以看出,数组是存储在编号键中的值(基于0从零),而对象是属性 - 值对。它们的共同点是comma (,)
分隔符。