javascript - Combine several JSON.stringify to one - Stack Overflow

admin2025-04-21  1

How do I bine strings with JSON.stringify?

This is not working:

var objA = {a: 5};

var objB = {b: 6};

var str = JSON.stringify(objA) + JSON.stringify(objB);

console.log(JSON.parse(str)); //error

,js,console

Expected output is: "[{\"a\":5},{\"b\":6}]"

How do I bine strings with JSON.stringify?

This is not working:

var objA = {a: 5};

var objB = {b: 6};

var str = JSON.stringify(objA) + JSON.stringify(objB);

console.log(JSON.parse(str)); //error

https://jsbin./yabacuyafe/edit?html,js,console

Expected output is: "[{\"a\":5},{\"b\":6}]"

Share Improve this question edited Feb 1, 2017 at 19:33 Joe asked Feb 1, 2017 at 19:18 JoeJoe 4,27432 gold badges106 silver badges180 bronze badges 0
Add a ment  | 

3 Answers 3

Reset to default 4

If your expected output is:

[{"a":5},{"b":6}]

Then use:

JSON.stringify([objA, objB])

If your expected output is:

{"a":5,"b":6}

Then use:

JSON.stringify(Object.assign({}, objA, objB))

I do not remend trying this with strings. Combine the objects first, then stringify.

var objA = {a: 5};

var objB = {b: 6};
var bined = {
    objA: objA,
    objB: objB
}

var str = JSON.stringify(bined);

console.log(JSON.parse(str));

If your expected output is (one object):

{"a":5,"b":6}

const objC = {...objA, ...objB };

var str = JSON.stringify(objC);
转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1745215984a290852.html

最新回复(0)