I am using jQuery's getJSON function to make a request and handle the JSON response. The problem is the response I get back is malformed and I can't change it. The response looks something like this:
{
aNumber: 200,
someText: '\'hello\' world',
anObject: {
'foo': 'fooValue',
'bar': '10.0'
}
}
To be valid JSON, it should look like this:
{
"aNumber": 200,
"someText": "'hello' world",
"anObject": {
"foo": "fooValue",
"bar": "10.0"
}
}
I would like to change the text returned to a valid JSON object. I've used the JavaScript replace function to turn the single quotes into double quotes and the escaped single quotes into single quotes, but now I am stuck on figuring out the best way to add quotes around the key values.
For example, how would I change foo: "fooValue"
to "foo":"fooValue"
? Is there a Regular Expression that can make this easy?
Thanks in advance!
Firstly, double quote character is nothing special in regex - it's just another character, so it doesn't need escaping from the perspective of regex. However, because Java uses double quotes to delimit String constants, if you want to create a string in Java with a double quote in it, you must escape them.
to show double quote you can simple use escape character("\") to show it.
Using the Escape Character ( \ ) The syntax of \' will always be a single quote, and the syntax of \" will always be a double quote, without any fear of breaking the string. Using this method, we can use apostrophes in strings built with " .
To place quotation marks in a string in your code In Visual Basic, insert two quotation marks in a row as an embedded quotation mark. In Visual C# and Visual C++, insert the escape sequence \" as an embedded quotation mark.
This regex will do the trick
$json = preg_replace('/([{,])(\s*)([A-Za-z0-9_\-]+?)\s*:/','$1"$3":',$json);
It's a php though! I assume it's not a problem converting it to JS.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With