6

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.

serv-inc
  • 35,772
  • 9
  • 166
  • 188
slacy
  • 11,397
  • 8
  • 56
  • 61

3 Answers3

10

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}
RanRag
  • 48,359
  • 38
  • 114
  • 167
  • 1
    @slacy I just noticed that yaml needs a space after colon.I think this will spoil your party. – RanRag Feb 01 '12 at 23:38
  • 1
    It does, unless the RHS is an array. {foo:[bar]} is fine, which is actually what I'm doing. – slacy Feb 01 '12 at 23:41
  • As RanRag said, yaml will fail if there is no space after colon, for example: `yaml.load('{a:"b"}')` – null Nov 26 '14 at 17:36
  • @suud: i still don't understand the downvote because I have clearly mentioned that yaml will fail in that particular scenario and OP was fine with it. So, why the downvote? – RanRag Nov 26 '14 at 18:01
  • Sometimes a question in SO despite looks like a specific question, it can be represented as general question, that's why you can see some questions here are marked as duplicated question. I have same question with the OP and I downvoted your answer because your solution is not perfect. Is it clear enough? :) – null Dec 01 '14 at 09:33
  • @suud : I got your point. Can you please share the perfect solution for this ? – RanRag Dec 02 '14 at 18:15
2

You can try demjson.

>>> import demjson
>>> demjson.decode('{foo:3}')
{u'foo': 3}
null
  • 8,669
  • 16
  • 68
  • 98
1

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}'
Andrew Clark
  • 202,379
  • 35
  • 273
  • 306