n1234
n1234

Reputation: 195

Parse Complex Json String

I'm attempting to parse the following JSON string (not in control of the format, I know it's hideous).

    var json = '{"what.1.does":"anything", "nestedjsonstr":"{\"whatup\":\"nada\"}"}';
    obj = JSON.parse(json);

I'm getting Error: Unexpected token w in JSON at position 43 which is where the first value of nestedjsonstr begins. Is there any elegant way to parse this?

Upvotes: 1

Views: 48

Answers (1)

MSclavi
MSclavi

Reputation: 427

Maybe this can help you out. You replace the curly braces inside your string without the ", and remove the \.

var json = '{"what.1.does":"anything", "nestedjsonstr":"{\"whatup\":\"nada\"}"}';

json = json.replace('\"{', '{').replace('}\"', '}').replace('\\"', '"');

obj = JSON.parse(json);
console.log(obj);

Upvotes: 1

Related Questions