Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 366
Sandeep Avatar asked Jun 21 '14 12:06

Sandeep


People also ask

Can you put variables in JSON?

Variables provide a new way to tackle different scenarios where JSON schema alone fails. This means, that you can use a new keyword named $vars to make your life easier.

Can you put JavaScript in JSON?

JSON FormatJSON's format is derived from JavaScript object syntax, but it is entirely text-based. It is a key-value data format that is typically rendered in curly braces.

What is [] and {} in JSON?

' { } ' used for Object and ' [] ' is used for Array in json.


2 Answers

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.

like image 114
André Pena Avatar answered Oct 12 '22 02:10

André Pena


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);
like image 33
chandu Avatar answered Oct 12 '22 01:10

chandu