0

I'm trying to convert a simple JSON string {\n 100: {"a": "b"}\n} to a python object but its giving me this error: Expecting property name enclosed in double quotes

Why is it insisting that the name of the attribute be a string?

>>> import simplejson
>>> my_json = simplejson.loads('{\n    100: {"a": "b"}\n}')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Users/myuser/myenv/lib/python2.7/site-packages/simplejson/__init__.py", line 525, in loads
    return _default_decoder.decode(s)
  File "/Users/myuser/myenv/lib/python2.7/site-packages/simplejson/decoder.py", line 370, in decode
    obj, end = self.raw_decode(s)
  File "/Users/myuser/myenv/lib/python2.7/site-packages/simplejson/decoder.py", line 400, in raw_decode
    return self.scan_once(s, idx=_w(s, idx).end())
simplejson.errors.JSONDecodeError: Expecting property name enclosed in double quotes: line 2 column 5 (char 6)
Saqib Ali
  • 11,931
  • 41
  • 133
  • 272
  • 2
    ...because that's part of the JSON format specification? "A name is a string.", from section 6 of https://www.ecma-international.org/publications/files/ECMA-ST/ECMA-404.pdf – Charles Duffy Mar 20 '20 at 17:30

1 Answers1

2

This value is invalid {100: {"a": "b"}}, you need {"100": {"a": "b"}}.

The property name there being 100 needs to be enclosed in double quotes so "100".

Why is it insisting that the name of the attribute be a string?

That's how JSON is.

You may have been used to be able to write {100: {"a": "b"}} in Javascript or another language, (without double quoting the property name), but you'll still get a parsing error if you try to parse it as JSON in Javascript, e.g.:

JSON.parse('{100: {"a": "b"}}')
SyntaxError: JSON.parse: expected property name or '}'
at line 1 column 2 of the JSON data
bakkal
  • 54,350
  • 12
  • 131
  • 107