1

I am trying to stringify the object which has another stringify object. I am getting \added to inside object

a   = {}
str = {'a': 'test'}
a.str = JSON.stringify(str);

console.log("=="+  (a));
console.log("strin " + JSON.stringify(a) ) // {"str":"{\"a\":\"test\"}"}


expected:  {"str":"{"a":"test"}"}
1
  • The extra slashes are just escaped characters, you can read more about it in the Escape notation section on this page Commented Nov 30, 2020 at 9:24

2 Answers 2

2

What you expect would not be valid JSON.

Quotes are used to delimit strings in a JSON text.

With your expected result a JSON parser would see "{" and think that was the whole string and then a would be an error.

The escape sequence \" is how you say "This is a quote that is a part of a string" instead of "This is a quote that ends the string".

The output is fine. There is nothing wrong.


That said, nesting JSON is generally a bad idea. It is more complicated to parse and harder to read.

In general you should be creating the complete data structure and then stringifying that.

const a = {};
const str = {
  'a': 'test'
};
a.str = str;
const json = JSON.stringify(a, null, 2);
console.log(`result: ${json}`);

Sign up to request clarification or add additional context in comments.

Comments

-1

There is an error

str = {'a': 'test}

It should be

str = {'a': 'test'}

The reason you are getting '' is simply because they are escaping double strings

This is illegal:

"{"str":"{"a":"test"}"}"

This is legal:

"{\"str\":\"{\"a\":\"test\"}\"}"

1 Comment

That looks like an error in the creation of the test case. It isn't the problem being asked about and cannot cause the problem described.

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.