简体   繁体   中英

inserting javascript variable value in json

i have a JSON variable which looks like this:

{"events": [
{"event_id": "1", "event_name": "Breakfast"},
{"event_id": "1", "event_name": "Calling Bob"}
]};

i have two vaiables

x=2; y=jam;

i want to push the variables in json such that x is event_id and y is event_name, so that my json will look like-

{"events": [
{"event_id": "1", "event_name": "Breakfast"},
{"event_id": "1", "event_name": "Calling Bob"},
{"event_id": "2", "event_name": "jam"}
]};

the function iam using to push is

k='({"event_id":"'+x+'","event_name":"'+y+'"})';
san.events.push(k);

where san is the variable in which i stored the json. iam parsing the variable san and applying the push action and stringifying it and displaying it, but in the result my json data syntax is changing like additional '/' symbols are generating in the json.

JSON objects are first class citizens in JavaScript, you can use them as literals.

var k= {"event_id": x, "event_name":y};
san.events.push(k);

As the above is the exact same thing as:

var k = new Object();
k.event_d = x;
k.event_name = y;
san.events.push(k);

JSON is just a way to represent regular objects in JavaScript.

If you really want to transform strings into JSON, you can use the JSON.parse() method, but you normally want to avoid this.

EDIT

As @Alvaro pointed out, even though you can create regular Objects using the JSON syntax, it's not synonym of Object, it' just a way of representing the Object data, and not just any data, JSON cannot represent recursive objects.

The variable value is missing Quote here

x=2; y='jam';

and change push code like this

k={"event_id":"'+x+'","event_name":"'+y+'"};
san.events.push(k);

here is solution for this problem.

san = {"events": [
{"event_id": "1", "event_name": "Breakfast"},
{"event_id": "1", "event_name": "Calling Bob"}
]};
var x=2; var y='am';
k={"event_id":"x","event_name":y};
san.events.push(k);
console.log(san);

http://jsfiddle.net/3NSy8/

Does this work for you?

x = "2";
y = "jam"
k= {"event_id": x, "event_name": y };
san.events.push(k);

Pass it inside a square bracket [ variable_name ]

Example:

let account_name = "premium_account"
{"features": { [account_name] :"checked"}}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM