Adding a new element to a JSON object using Javascript

Feedback

Question:

Let’s assume that I possess a
JSON object
that looks like this:

{"name":"asdf","quantity":"3","_id":"v4njTN7V2X10FbRI"}

Once it is created, there is no possibility of me making any modifications to it. However, my aim is to alter its appearance to resemble this specific format.

{"name":"asdf","quantity":"3","_id":"v4njTN7V2X10FbRI", checked: true}

What is the approach to execute it using JavaScript?


Solution 1:

When it comes to JavaScript, the term ”
JSON Object
” does not exist. Rather, we refer to JavaScript itself. While
objects. JSON
is based on the syntax of JavaScript, it is considered a
data interchange format
. In JavaScript, an object is simply an object and you can add a property to it by executing the relevant code.

var object = {"name":"asdf","quantity":"3","_id":"v4njTN7V2X10FbRI"};
object.checked = true;

If the string you possess contains
JSON-serialized object
, then the appropriate action would be to deserialize it, include the property, and serialize it again.


Solution 2:


Based on how you have currently framed your inquiry.

> 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}

It’s possible that you need to perform decoding and encoding before proceeding.

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));

Frequently Asked Questions