javascript - Format to JSON with regex -
i have read file json appearance, , format similar following:
{ varparent1: { var1: true, var2: "this string", var3: 0, var4: "another string" }, varparent2:{ var1: false, var2: 0, var3: 92, var4: "string here", var5: "string2 here" } }
i have code in variable, can't edit file, should work variable.
as can see, not valid format json, not being able parse it. need format this:
{ "varparent1": { "var1": true, "var2": "this string", "var3": 0, "var4": "another string" }, "varparent2":{ "var1": false, "var2": 0, "var3": 92, "var4": "string here", "var5": "string2 here" } }
i have thought logic , have conclusion (i think it's fine): have add '"' start , end of every line , between ":" too. i'm not able regex.
is there easier way?
this:
var json = text.replace(/([a-za-z0-9]+)\:/g, "\"$1\":");
works example, if string value contains colon, you're in trouble.
for more general solution, can start separating string literals rest, apply replace on non-strings, concatenate again:
var nonstrings = [], strings = []; var re = /"(?:[^"\\]|\\.)*"/g; var rs; var start = 0; while (rs = re.exec(text)) { var end = rs.index; nonstrings.push(text.substring(start,end)); strings.push(rs[0]); start = end + rs[0].length; } nonstrings.push(text.substring(start)); console.log(nonstrings); console.log(strings); (var = 0; < nonstrings.length; ++i) { nonstrings[i] = nonstrings[i].replace(/([a-za-z0-9]+)\:/g, "\"$1\":"); } var json = nonstrings[0]; (var = 0; < strings.length; ++i) { json += strings[i] + nonstrings[i+1]; } console.log(json);
update:
you can simplify merging different passes:
var re = /"(?:[^"\\]|\\.)*"/g; var rs; var start = 0; var json = ""; while (rs = re.exec(text)) { var end = rs.index; json += text.substring(start,end).replace(/([a-za-z0-9]+)\:/g, "\"$1\":") + rs[0]; start = end + rs[0].length; } json += text.substring(start).replace(/([a-za-z0-9]+)\:/g, "\"$1\":"); console.log(json);
Comments
Post a Comment