So say I have a JSON object like this:
{"name":"asdf","quantity":"3","_id":"v4njTN7V2X10FbRI"}
And I can't modify it when it is created. But I want to make it look like this:
{"name":"asdf","quantity":"3","_id":"v4njTN7V2X10FbRI", checked: true}
So how would I do that with javascript?
-
1You would do that in JavaScript by reading a basic tutorial on JS, including JS objects and how to assign properties to them.user663031– user6630312014年12月06日 17:56:14 +00:00Commented Dec 6, 2014 at 17:56
-
possible duplicate of Add new attribute (element) to JSON object using JavaScriptQuintin Robinson– Quintin Robinson2014年12月06日 17:58:54 +00:00Commented Dec 6, 2014 at 17:58
2 Answers 2
In the context of JavaScript, there's no such thing as a "JSON Object". What you've got there are JavaScript objects. JSON is a data interchange format that was of course derived from JavaScript syntax, but in JavaScript directly an object is an object. To add a property, just do so:
var object = {"name":"asdf","quantity":"3","_id":"v4njTN7V2X10FbRI"};
object.checked = true;
Now, if what you've really got is a string containing a JSON-serialized object, then the thing to do is deserialize, add the property, and then serialize it again.
With the way your question is currently structured:
> myJson = {"name":"asdf","quantity":"3","_id":"v4njTN7V2X10FbRI"}
Object {name: "asdf", quantity: "3", _id: "v4njTN7V2X10FbRI"}
> myJson.checked = true;
true
> myJson
Object {name: "asdf", quantity: "3", _id: "v4njTN7V2X10FbRI", checked: true}
But I bet you may have to decode and recode first with:
JSON.parse(myJson)
JSON.stringify(myJson)
The entire thing may look like
// get json and decode
myJson = JSON.parse(response);
// add data
myJson.checked = true;
// send new json back
$.post('/someurl/', JSON.stringify(myJson));
-
-
@Pointy yes it is. Just updated; thanks for the catch.agconti– agconti2014年12月06日 18:23:49 +00:00Commented Dec 6, 2014 at 18:23
-
@torazaburo do you really believe that adding the additional information about serializing / deserializing json is worth a downvote? The OP is asking about json, so its reasonable to assume he might have to serialize it once he's done adding the new value. You have no grounds to suggest that he isn't sending or receiving anything from a server in his actual application.agconti– agconti2014年12月06日 18:28:37 +00:00Commented Dec 6, 2014 at 18:28
-
@torazaburo than deal with the question in that way; don't take your frustrations out on others who are trying to help people.agconti– agconti2014年12月06日 18:40:45 +00:00Commented Dec 6, 2014 at 18:40