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?

1

2 Answers 2

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}))
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.