I have String like
"[{'techid':'0128','daPoints':3,'speedingPoints':3,'fleetInspectionPoints':3,'lofPoints':3,'missedTrgModules':null,'fullName':'MANPREET SINGH','safetyInspectPoints':3,'missedTrgPoints':3,'speeding_qty':null,'safetyTotalPoints':21,'atFaultPoints':3,'atFaultAccident':null,'region':'PYEM','supervisor':'AGHATOR OSA','driverAlert':null,'status':'A'}]"
need to convert into Json format
trying something like this
const text = "[{'techid':'0128','daPoints':3,'speedingPoints':3,'fleetInspectionPoints':3,'lofPoints':3,'missedTrgModules':null,'fullName':'MANPREET SINGH','safetyInspectPoints':3,'missedTrgPoints':3,'speeding_qty':null,'safetyTotalPoints':21,'atFaultPoints':3,'atFaultAccident':null,'region':'PYEM','supervisor':'AGHATOR OSA','driverAlert':null,'status':'A'}]";
const myArr = JSON.parse(text);
document.getElementById("demo").innerHTML = myArr[0];
But getting error :-
Uncaught SyntaxError: Expected property name or '}' in JSON at position 2
2
Answers
Simple Solution:
Convert all of the single-quoted strings and properties (that are invalid JSON in the specification) to valid JSON with double-quotes using a Regular Expression (RegExp):
Update:
Over-Engineered Solution: Literally an entire parser…
It should be well commented enough to be able to use and modify to anyone’s needs. GitHub repo (Permalink)
WARNING: In brute-force mode can be
O(2^n)
! Which is very inefficient.The presence of incorrect string delimiters causes ambiguity during parsing. And useful solutions are very computationally expensive.
The OP is in need of a sanitizing
replace
task where the used regex needs to explicitly target the single quotes around any property name and any string value. Thus such a regex has to utilize both a positive lookbehind and a positive lookahead. It would look as follows …… and its functioning is described at its playground page.
For environments which do not support lookbehinds like current Safari’s one has to change the approach to two different regex patterns each featuring a capturing group for either the leading …
/([,{:])'/g
… or the trailing …/'([:,}])/g
… character of a to be replaced single quote.The above provided example code then changes to …