Javascript 将项目添加到 JSON 字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14566071/
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
Add item to JSON string
提问by Valeriane
I create JSONobject as:
我创建JSON对象为:
var myJsonObject = JSON.stringify(objectString)
How I can add another item into myJsonObject??
我如何才能将另一个项目添加到myJsonObject??
回答by Naftali aka Neal
myJsonObjectis now a stringyou cannot add anything to it again until you change it backinto a JSON object.
myJsonObject现在是一个字符串,你不能再向它添加任何东西,直到你把它改回一个 JSON 对象。
So you cantechnically do:
所以你可以在技术上做到:
var myJsonObject = JSON.parse(myJsonObject); //change to obj
myJsonObject.somethingnew = true; //add something
myJsonObject = JSON.stringify(myJsonObject); //change back to string
回答by ChrisIPowell
Looks like you're re-serializing the string rather than parsing it.
看起来您正在重新序列化字符串而不是解析它。
var myJsonObject = JSON.parse(objectString);
then you can add a new item by using
然后您可以使用添加新项目
myJsonObject['newItemName'] = newValue;
Hope that's clear.
希望这很清楚。
回答by AlexStack
If you mean you want to have an array of objects, you can do it like this:
如果你的意思是你想要一个对象数组,你可以这样做:
//create an array with the result of your object (see the [] characters)
var myJsonArrayObject = JSON.stringify( [ objectString ] );
//add a new element to the array: parse the JSON, push the new element and stringify again:
JSON.stringify( JSON.parse( myJsonArrayObject ).push( newObject ) );

