0

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?

Pointy
  • 405,095
  • 59
  • 585
  • 614
thelearnerofcode
  • 326
  • 3
  • 4
  • 9
  • 1
    You would do that in JavaScript by reading a basic tutorial on JS, including JS objects and how to assign properties to them. –  Dec 06 '14 at 17:56
  • possible duplicate of [Add new attribute (element) to JSON object using JavaScript](http://stackoverflow.com/questions/736590/add-new-attribute-element-to-json-object-using-javascript) – Quintin Robinson Dec 06 '14 at 17:58

2 Answers2

5

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.

Pointy
  • 405,095
  • 59
  • 585
  • 614
2

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));
agconti
  • 17,780
  • 15
  • 80
  • 114
  • Isn't it `JSON.parse()`? – Pointy Dec 06 '14 at 18:20
  • @Pointy yes it is. Just updated; thanks for the catch. – agconti Dec 06 '14 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 Dec 06 '14 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 Dec 06 '14 at 18:40