简体   繁体   中英

JSON.stringify with square brackets

I have a JS object:

var source = {};
source.quantity = 1;
source.text = 'test';

Now I JSON it:

var json = JSON.stringify(source);

json looks like this:

{"quantity":"1","text":"test"}

I would like it to be like this:

[{"quantity":"1"},{"text":"test"}]

Ho can I do this?

Get all the keys as an Array them map them to Objects as key-value pairs from source

JSON.stringify(
    Object.keys(source)
          .map(
              function (e) {
                  var o = {};
                  o[e] = source[e];
                  return o;
              }
          )
); // "[{"quantity":1},{"text":"test"}]"
var json = JSON.stringify([
    {quantity: "1"},
    {text: "test"}
]);

I guess this is not possible but you can do this:

var source = {};
source.quantity = 1;
source.text = 'test';

var result = [];

for(var i in source) {
    var obj = {};
    obj[i] = source[i];
    result.push(obj);
}

var json = JSON.stringify(result);

I hope this can help you.

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