Joe
Joe

Reputation: 4234

Combine several JSON.stringify to one

How do I combine 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.com/yabacuyafe/edit?html,js,console

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

Upvotes: 1

Views: 4387

Answers (3)

Viorel
Viorel

Reputation: 83

If your expected output is (one object):

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

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

var str = JSON.stringify(objC);

Upvotes: 0

000
000

Reputation: 27247

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 recommend trying this with strings. Combine the objects first, then stringify.

Upvotes: 4

Mike
Mike

Reputation: 787

var objA = {a: 5};

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

var str = JSON.stringify(combined);

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

Upvotes: 2

Related Questions