Is there any way to make simplejson less strict?

3.2k views Asked by At

I'm interested in having simplejson.loads() successfully parse the following:

{foo:3}

It throws a JSONDecodeError saying "expecting property name" but in reality it's saying "I require double quotes around my property names". This is annoying for my use case, and I'd prefer a less strict behavior. I've read the docs, but beyond making my own decoder class, I don't see anything obvious that changes this behavior.

3

There are 3 answers

6
RanRag On BEST ANSWER

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

>>> import yaml
>>> s = '{foo: 8}'
>>> yaml.load(s)
{'foo': 8}
0
null On

You can try demjson.

>>> import demjson
>>> demjson.decode('{foo:3}')
{u'foo': 3}
0
Andrew Clark On

No, this is not possible. To successfully parse that using simplejson you would first need to transform it into a valid JSON string.

Depending on how strict the format of your incoming string is this could be pretty simple or extremely complex.

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

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

For example:

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