简体   繁体   中英

How frame Json object dynamically with dynamic key and value strings

i have a json i want to add key value pairs (after framing the below format) like

var json = {};
var a = '"key1" : "value1"'; //coming as dynamic
var b = '"key2" : "value2"'; // coming as dynamic
json.push(a); // i know it is wrong.
json.push(b); // i know it is wrong.
console.log(json); // {"key1": "value1", "key2": "value2"} expected

var array = [];
var c = '{"key1": "value1"}';
var d = '{"key2": "value2"}';
array.push(c);
array.push(d);
console.log(array); // ["{"key1": "value1"}", "{"key2": "value2"}"] 

like the above i can push objects to array, but how can i push json strings directly to a json object.

Firstly a little clarification; there's no such thing as a 'JSON object'. There is a JSON-formatted string, and there is an object. They are two separate entities.

To add strings to an object, specify the property of the object and set its value. You don't need push() for this as that is used exclusively for arrays. In your case, it should look like this:

var obj = {};
obj.key1 = "value1";
obj.key2 = "value2";
console.log(obj); // = { "key1": "value1", "key2": "value2" }

To set a key dynamically use bracket notation:

var key = 'foo';
obj[key] = 'bar';
console.log(obj); // = { 'foo': 'bar' }

If you need to then convert the object to a JSON string, call JSON.stringify on that object:

var json = JSON.stringify(obj);

Also note that in your second example you end up with an array of strings, not an array of objects. If you want an array of objects you need to remove the quotes around the values you set, like this:

var array = [];
var c = { "key1": "value1" };
var d = { "key2": "value2" };
array.push(c);
array.push(d);
console.log(array); // [{ "key1": "value1" }, { "key2": "value2" }] 

Note the difference in the position of the quotes in the objects and the result from the console.

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