Luis Diego Rojas
Luis Diego Rojas

Reputation: 202

JSON string containing \" after applying JSON.parse

I´m receiving a message that I have to parse to create a JSON object from a .NET application in javascript, but when I parse the message using the following instructions:

var messagePropertiesString  = JSON.stringify(messageObject.json);
var messageProperties = JSON.parse(messagePropertiesString);

The results contains a backslash, so I´m not able to convert it to a JSon object since it has the backslash.

{\"TravelNumber\":1,\"Unit\":\"g\",\"Weight\":0}

How can I remove the extra backslash?

Upvotes: 0

Views: 240

Answers (1)

Paul
Paul

Reputation: 141839

messageObject.json is already a string, so there is no need to stringify it, and when you do you get a string that would need to be parsed twice (the first parse will just undo the stringify and get you back a string of JSON) to get an object:

var messagePropertiesString  = JSON.stringify( messageObject.json );
var messageProperties = JSON.parse( JSON.parse( messagePropertiesString ) );

Instead, you should skip the stringify, and just parse it once:

var messageProperties = JSON.parse( messageObject.json );

Upvotes: 3

Related Questions