Reputation: 371
I've created an application that's reading data from http response. The data comes back as JSON and the JSON string contains backslashes where the double quotes are escaped.
I've tried the example demonstrated here, Android: Parsing JSON string inside of double quotes.
Here's my example:
var data="\"[{\\\"FirstName\\\":\\\"John\\\",\\\"LastName\\\":\\\"Doe\\\"}]\""
var escapeSlashes = data.replace("\\\"/g", "\"");
It returns like this:
[{\"FirstName\":\"John\",\"LastName\":\"Doe\"}]
The code breaks when trying to parse.
var obj = $.parseJSON(escapeSlashes);
Is there another way of handling this other than doing a replace?
Upvotes: 1
Views: 2965
Reputation: 18861
Alright, so.. it's really just JSON, escaped several times. Super silly thing to do, but how to solve this?
Let's unescape it several times!
Here we go:
var moo = "\"[{\\\"FirstName\\\":\\\"John\\\",\\\"LastName\\\":\\\"Doe\\\"}]\"";
// Don't let the backslashes confuse you
// What the string really contains is here:
console.log(moo);
// "[{\"FirstName\":\"John\",\"LastName\":\"Doe\"}]"
// That's a JSON string, see the quotes at the ends?
// Let's parse!
var moo2 = JSON.parse(moo);
console.log(moo2);
// [{"FirstName":"John","LastName":"Doe"}]
// Alright, looks like a regular JSON array with one object in it.
// Crack it open!
var moo3 = JSON.parse(moo2);
console.log(moo3);
// Hole cow, we got a JS Object!
// [Object { FirstName="John", LastName="Doe"}]
// Do whatever you want with it now...
Try it out: http://jsfiddle.net/YC6Hx/
Upvotes: 3