0

Problem with JSON.parse in nested json object string

I have a author object as:

var a = {"firstName":"abhi", "lastName":"pat"}

Am using the JSON parse with other data as:

JSON.parse(`{"name": "u", "author": "${a}"}`)

I got the the output as:

{name: "u", author: "[object Object]"}

The expected output is:

{name: "u", author: {firstName: "abhi", lastName: "pat"}}

Can anyone suggest me the right way to parse it?

  • Does this answer your question? [JSON.parse returning \[Object Object\] instead of value](https://stackoverflow.com/questions/47737093/json-parse-returning-object-object-instead-of-value) – Jonathan Stellwag Feb 24 '20 at 18:15

2 Answers2

1

You need to stringify a, not put it directly into the JSON.

JSON.parse(`{"name": "u", "author": ${JSON.stringify(a)}}`)

But you shouldn't contruct JSON directly as a string in the first place, you should use JSON.stringify() for the whole thing:

JSON.parse(JSON.stringify({name: "u", author: a}))
Barmar
  • 741,623
  • 53
  • 500
  • 612
0

You can use other methods for object assign:

var a = {"firstName":"abhi", "lastName":"pat"}
console.log({"name": "u", "author": Object.assign({}, a)});

No need JSON.parse or JSON.stringify methods.

Sukanta Bala
  • 871
  • 1
  • 9
  • 19