Regular expression for adding double quotes around keys in javascript

I am using the jQuery getJSON function to make a request and process a JSON response. The problem is that the answer I get is distorted and I cannot change it. The answer looks something like this:

{ aNumber: 200, someText: '\'hello\' world', anObject: { 'foo': 'fooValue', 'bar': '10.0' } } 

To be valid JSON, it must look like this:

 { "aNumber": 200, "someText": "'hello' world", "anObject": { "foo": "fooValue", "bar": "10.0" } } 

I would like to change the text returned by a valid JSON object. I used the javascript replacement function to turn single quotes into double quotes and escaped single quotes into single quotes, but now I'm stuck in finding a better way to add quotes around key values. For example, how do I change foo: "fooValue" to "foo": "fooValue"? Is there a regex that can make this easier?

Thanks in advance!

+4
source share
5 answers

edit - returned to indicate, first of all, that this is not a problem that can be solved with a regular expression.

It is important to distinguish between JSON notation as serialized form and JavaScript constant notation.

It:

 { x: "hello" } 

is a perfectly valid JavaScript value (expression fragment), so this is:

 var y = { x: "hello" }; 

gives exactly the same result as:

 var y = { "x": "hello" }; 

In other words, the value of "y" in any of these cases will be exactly the same. In the exact same way, so it would be impossible to ever say which of these two constants was used to initialize the "y".

Now, if what you want to do is translate the line containing the JSON shorthand JavaScript style, without the quotes in the actual JSON, the only thing to do is parse it and restore the quotation line around the property names. That is, you will have to either write your own “relaxed” JSON parser than deal with unquoted identifiers as property names, or find a ready-made parser that can handle such a relaxed syntax.

In your case, it looks like once you have an accessible "relaxed" parser, everything is ready; you will not need to translate back. Fortunately, your "invalid" JSON response is completely interpreted by JavaScript itself, so if you trust the data source (and that big if), you should be able to evaluate it with "eval ()".

+3
source

This regex will do the trick

 $json = preg_replace('/([{,])(\s*)([A-Za-z0-9_\-]+?)\s*:/','$1"$3":',$json); 

This is php though! I guess this is not a problem converting it to JS.

+8
source

I tried to solve the same problem using regEx in Javascript. I have an application written for Node.js to parse incoming JSON, but you need a “relaxed” version of the parser (see the following comments), since it is inconvenient to put quotes around each key (name). Here is my solution:

 var objKeysRegex = /({|,)(?:\s*)(?:')?([A-Za-z_$\.][A-Za-z0-9_ \-\.$]*)(?:')?(?:\s*):/g;// look for object names var newQuotedKeysString = originalString.replace(objKeysRegex, "$1\"$2\":");// all object names should be double quoted var newObject = JSON.parse(newQuotedKeysString); 

Here's a breakdown of regEx:

  • ({|,) searches for the beginning of the object, { for flat objects or , for embedded objects.
  • (?:\s*) finds, but does not remember, a space.
  • (?:')? finds, but does not remember a single quote (which will be replaced by a double quote later). There will be either zero or one of them.
  • ([A-Za-z_$\.][A-Za-z0-9_ \-\.$]*) Is the name (or key). Begins with any letter, underscore, $ or period followed by zero or more alphanumeric characters or underscores or dashes or periods or $.
  • last character : - this is what restricts the name of the object from the value.

Now we can use replace() with some bandage to get our recently quoted keys:

 originalString.replace(objKeysRegex, "$1\"$2\":") 

where $1 is either { , or , depending on whether the object was embedded in another object. \" adds a double quote. $2 is the name. \" another double quote. and finally : shutting down. Test it with

 {keyOne: "value1", $keyTwo: "value 2", key-3:{key4:18.34}} 

output:

 {"keyOne": "value1","$keyTwo": "value 2","key-3":{"key4":18.34}} 

Some comments:

  • I have not tested this method for speed, but from what I collect while reading some of these entries is that using regex is faster than eval()
  • For my application, I restrict the characters whose names are allowed for ([A-Za-z_$\.][A-Za-z0-9_ \-\.$]*) For my "relaxed" JSON parser. If you want to allow more characters in names (you can do it and still have valid JSON), you can use ([^'":]+) instead to indicate anything other than double or single quotes or a colon This will still limit you to the JSON standard (which allows single quotes in a name), but then you cannot parse this method. Here you can have all kinds of things with this expression ([^'":]+) , so be careful.

Hope this helps.

+7
source

You do not need to do this - you already have a valid JSON object. Read the 'bout JSON here .

If you need to get the value, you just write data.whatever , and it just works. For example: if you have a JSON data object :

 { moo: "foo", foo: "bar" } 

All possible fields are moo and foo and their use is data.moo and data.foo respectively. And if you want to use data as a jQuery argument, you just pass it as-is: $.load("http://my.site.com/moo", data, function(response){ /* ... */ }) .

Note: in the last example I mentioned, the answer will be a string. To make it a valid JSON object, use the $.parseJSON(response); method $.parseJSON(response); .

0
source

Since this is the wrong "JSON", you cannot use jQuery.getJSON.

you can use

 jQuery.ajax({ url : myUrl, data : myParams, type : "GET", success : function(jsontext) { // jsontext is in text format jsontext = jsontext.replace("'", "\""); // now convert text to JSON object var jsonData = eval('(' + jsontext+ ')'); // rest of the code } }); 
0
source

Source: https://habr.com/ru/post/1337668/


All Articles