I
I
Ivan Korsakov2016-06-28 13:25:59
JavaScript
Ivan Korsakov, 2016-06-28 13:25:59

How can I replace single quotes with double quotes in invalid JSON?

But you also need to take into account that in JSON there are pieces of html code with doubles that are nested in singles (at the moment).

Thanks everyone for the replies!

Answer the question

In order to leave comments, you need to log in

2 answer(s)
E
Eugene, 2016-06-28
@AppFA

Maybe not the best solution, but in haste:

'use strict';

const invalidJSON = `{"root": {'html': '<div class="header1"></div>', 'fragment': '<div class="footer"></div>'}}`;

let validJSON = invalidJSON.replace(/'/g, '"');
validJSON = validJSON.replace(/="+[A-z0-9]*"/g, (str) => {
    return str.replace(/"/g, '\\"');
});

console.log(validJSON);
// => {"root": {"html": "<div class=\"header1\"></div>", "fragment": "<div class=\"footer\"></div>"}}

N
napa3um, 2016-06-28
@napa3um

If the JSON is from a controlled source (i.e. it is not known to contain destructive code), then you can do this:

var badJson = "{'foo': 'bar'}";
var goodJson = JSON.stringify(eval('(function(){return ' + badJson + ';})()'));

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question