Insert javascript variable value in json

I have a JSON variable that 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 variables in json so x is event_id and y is event_name, so 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"}
]};

iam function used to click,

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

where san is the variable i kept json in. iam parses the san variable and applies a push action and builds and displays it, but as a result, the syntax of the json syntax changes, since additional "/" characters are generated in json.

+4
source share
4 answers

Variable value is missing Quote

x=2; y='jam';

and change the push code this way

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

JSON JavaScript, .

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

, , :

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

JSON - JavaScript.

JSON, JSON.parse(), .

@Alvaro, JSON, Object, Object, , JSON .

+2

here is the solution to 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/

+2
source

Does this work for you?

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

Source: https://habr.com/ru/post/1545477/


All Articles