Reputation: 1532
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.
Upvotes: 9
Views: 33676
Reputation: 83
Pass it inside a square bracket [variable_name]
Example:
let account_name = "premium_account"
{"features": { [account_name] :"checked"}}
Upvotes: 2
Reputation: 2276
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);
Upvotes: 4
Reputation: 369
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);
Upvotes: 1
Reputation: 59336
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.
Upvotes: 6
Reputation: 1563
Does this work for you?
x = "2";
y = "jam"
k= {"event_id": x, "event_name": y };
san.events.push(k);
Upvotes: 1