Is there a way to make simplejson less strict?

I am interested in simplejson.loads() successfully simplejson.loads() following:

 {foo:3} 

It throws a JSONDecodeError message saying "pending property name", but actually it says: "I need double quotes around the names of my properties." This annoys my use case, and I would prefer a less rigorous job. I read the documents, but apart from creating my own decoder class, I don't see anything obvious changing this behavior.

+6
source share
3 answers

You can use YAML (> = 1.2) since it is a superset of JSON, you can do:

 >>> import yaml >>> s = '{foo: 8}' >>> yaml.load(s) {'foo': 8} 
+10
source

You can try demjson .

 >>> import demjson >>> demjson.decode('{foo:3}') {u'foo': 3} 
+2
source

No, It is Immpossible. To successfully parse this using simplejson, you first need to convert it to a valid JSON string.

Depending on how strict your input line format is, this can be quite simple or extremely complex.

For the simple case, if you always have a JSON object that has only letters and underscores in keys (without quotes) and integers as values, you can use the following to convert it to real JSON:

 import re your_string = re.sub(r'([a-zA-Z_]+)', r'"\1"', your_string) 

For instance:

 >>> re.sub(r'([a-zA-Z_]+)', r'"\1"', '{foo:3, bar:4}') '{"foo":3, "bar":4}' 
+1
source

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


All Articles