如何使用 jQuery 或 JavaScript 在 JSON 中添加新对象?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9971333/
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
How to add new object in JSON using jQuery or JavaScript?
提问by pargan
I want to add new obj of JSON
like:
我想添加JSON
类似的新对象:
"128": {
"Msg": [{
"me": "hi"
}, {
"user": "hello"
}, {
"me": "whtup"
}]
}
In the exist JSON
object Example of JSON
:
在现有JSON
对象示例中JSON
:
{
"188": {
"Msg": [{
"me": "hi"
}, {
"user": "hello"
}, {
"me": "ki chal riha hai"
}]
},
"123": {
"Msg": [{
"me": "hi"
}, {
"user": "hello"
}, {
"me": "whtup"
}]
},
"128": {
"Msg": [{
"me": "hi"
}, {
"user": "hello"
}, {
"me": "whtup"
}]
}
回答by Jashwant
JSON stands for JavaScript object notation. So, it's nothing but an object ( actually a subset of object ) in javascript.
JSON 代表 JavaScript 对象表示法。所以,它只不过是 javascript 中的一个对象(实际上是 object 的一个子集)。
So, actually you want to add an object in existing javascript object.
所以,实际上你想在现有的 javascript 对象中添加一个对象。
Also, jQuery is nothing but a library (collections of different javascript functions to ease selecting dom elements, ajax functions, and some other utilities)
此外,jQuery 只不过是一个库(不同 javascript 函数的集合,以简化选择 dom 元素、ajax 函数和一些其他实用程序)
Coming back to your question,
回到你的问题,
If this is your existing object,
如果这是您现有的对象,
var obj = {
"188": {
"Msg": [{
"me": "hi"
}, {
"user": "hello"
}, {
"me": "ki chal riha hai"
}]
},
"123": {
"Msg": [{
"me": "hi"
}, {
"user": "hello"
}, {
"me": "whtup"
}]
},
"128": {
"Msg": [{
"me": "hi"
}, {
"user": "hello"
}, {
"me": "whtup"
}]
}
}
You can add
你可以加
var objToAdd = {
"Msg": [{
"me": "hi"
}, {
"user": "hello"
}, {
"me": "whtup"
}]
}
by,
经过,
obj["128"] = objToAdd;
Now, your obj
is,
现在,你的obj
是,
{
"188": {
"Msg": [{
"me": "hi"
}, {
"user": "hello"
}, {
"me": "ki chal riha hai"
}]
},
"123": {
"Msg": [{
"me": "hi"
}, {
"user": "hello"
}, {
"me": "whtup"
}]
},
"128":{
"Msg": [{
"me": "hi"
}, {
"user": "hello"
}, {
"me": "whtup"
}]
}
}