Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
905 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...