Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular Expression to add double quotes around keys in JavaScript

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!

like image 392
Evil E Avatar asked Jan 30 '11 15:01

Evil E


People also ask

How do you add double quotes in regex?

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.

How do you write double quotes in JavaScript?

to show double quote you can simple use escape character("\") to show it.

How do you append quotes in JavaScript?

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 " .

How do you mention double quotes in a string?

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.


1 Answers

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.

like image 164
Guy Avatar answered Nov 13 '22 06:11

Guy