rekha
rekha

Reputation: 11

Stringify the object getting "\"

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"}"}

Upvotes: 1

Views: 182

Answers (2)

Quentin
Quentin

Reputation: 943516

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}`);

Upvotes: 2

takunda madechangu
takunda madechangu

Reputation: 147

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\"}\"}"

Upvotes: -1

Related Questions