convert "converted" object string to JSON or Object
Asked Answered
C

3

0

i've following problem and since i upgraded my prototypeJS framework.

the JSON parse is not able anymore to convert this string to an object.

"{empty: false, ip: true}"

previously in version 1.6 it was possible and now it needs to be a "validated" JSON string like

'{"empty": false, "ip": true}'

But how can i convert the 1st example back to an object?

Clunk answered 24/1, 2011 at 11:5 Comment(0)
U
7

JSON needs all keys to be quoted, so this:

"{empty: false, ip: true}"

is not a valid JSON. You need to preprocess it in order to be able to parse this JSON.

function preprocessJSON(str) {

    return str.replace(/("(\\.|[^"])*"|'(\\.|[^'])*')|(\w+)\s*:/g,
    function(all, string, strDouble, strSingle, jsonLabel) {
        if (jsonLabel) {
            return '"' + jsonLabel + '": ';
        }
        return all;
    });

}

(Try on JSFiddle) It uses a simple regular expression to replace a word, followed by colon, with that word quoted inside double quotes. The regular expression will not quote the label inside other strings.

Then you can safely

data = JSON.parse(preprocessJSON(json));
Unbowed answered 24/1, 2011 at 11:30 Comment(4)
thanks for that quick response but i get a SyntaxError: unterminated parenthetical and i cannot figure it out i guess the regexp is mistyped somehow...Clunk
You are right. I corrected the regexp. I somehow removed the closing parenthesis by accident before posting this, it is now fixed. Thank you for spotting this!Unbowed
yep now it works, thanks alot - this solution might be better than the eval hookup :)Clunk
Genius, thank you. I wished I had more thoroughly searched for your script before embarking on dead ends!Dysprosium
P
1

It makes sense that the json parser didn't accept the first input as it is invalid json. What you are using in the first example is javascript object notation. It's possible to convert this to an object using the eval() function.

var str = "({empty: false, ip: true})";
var obj = eval(str);

You should of course only do this if you have the guarantees the code you'll be executing is save. You can find more information about the json spec here. A json validator can be found here.

edit: Thai's answer above is probably a better solution

Pregnancy answered 24/1, 2011 at 11:19 Comment(1)
You need to add parens in order for the JavaScript engine to see it as an object, not a block. eval('(' + str + ')').Unbowed
C
0
const dataWithQuotes = str.replace(/("(\\.|[^"])*"|'(\\.|[^'])*')|(\w+)\s*:/g, (all, string, strDouble, strSingle, jsonLabel) => {
  if (jsonLabel) {
    return `"${jsonLabel}": `;
  }
  return all;
});

return dataWithQuotes

similar solution as above , but updated with arrow functions.

Civilize answered 15/4, 2020 at 13:48 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.