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.
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.
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.
' { } ' used for Object and ' [] ' is used for Array in 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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With