Convert the "converted" string of an object to JSON or Object

I had the following problem and updated my prototypeJS framework.

JSON parse can no longer convert this string to an object.

"{empty: false, ip: true}" 

earlier in version 1.6 it was possible, and now it should be a "checked" JSON string, for example

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

But how can I convert the first example back to an object?

0
source share
2 answers

JSON requires all keys to be specified, so this is:

 "{empty: false, ip: true}" 

is not valid JSON. You need to pre-process 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 JSFiddle) It uses a simple regular expression to replace a word followed by a colon, with that word quoted inside double quotes. A regular expression will not indicate a label inside other lines.

Then you can calmly

 data = JSON.parse(preprocessJSON(json)); 
+6
source

It makes sense that json parser did not accept the first input as it is not valid json. What you use in the first example is the javascript object designation. You can convert this to an object using the eval() function.

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

You should, of course, do this only if you have guarantees that the code that you will execute will be saved. You can find more information about json spec here . Json validator can be found here .

edit: thai answer above is probably the best solution

+1
source

Source: https://habr.com/ru/post/1337669/


All Articles