问题
Hi I am working with JSON in my file in Python:
import json
userData = '''[
{
"userID" : "20",
"devices" : {
"360020000147343433313337" : "V33_03",
"3f0026001747343438323536" : "Door_03",
"170035001247343438323536" : "IR_06",
"28004c000651353530373132" : "BED_17"
}
},
]'''
info = json.loads(userData)
I get this error when I load it: json.decoder.JSONDecodeError: Expecting value:
or sometimes when I add something: json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes:
回答1:
Try using the ast
module
Ex:
import ast
userData = '''[
{
"userID" : "20",
"devices" : {
"360020000147343433313337" : "V33_03",
"3f0026001747343438323536" : "Door_03",
"170035001247343438323536" : "IR_06",
"28004c000651353530373132" : "BED_17"
}
},
]'''
info = ast.literal_eval(userData)
print(info)
回答2:
Looks the format is incorrect.
userData = '''[
{
"userID" : "20",
"devices" : {
"360020000147343433313337" : "V33_03",
"3f0026001747343438323536" : "Door_03",
"170035001247343438323536" : "IR_06",
"28004c000651353530373132" : "BED_17"
}
}, <--- remove this ","
]'''
See my test:
>>> import json
>>> json.loads('[{"a":"b"}]')
[{u'a': u'b'}]
>>> json.loads('[{"a":"b"},]')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Python27\lib\json\__init__.py", line 338, in loads
return _default_decoder.decode(s)
File "C:\Python27\lib\json\decoder.py", line 366, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "C:\Python27\lib\json\decoder.py", line 384, in raw_decode
raise ValueError("No JSON object could be decoded")
ValueError: No JSON object could be decoded
>>>
回答3:
For future reference, below how to get the JSON content or to get some spam:
import requests
url = 'http://httpbin.org/status/200'
r = requests.get(url)
if 'json' in r.headers.get('Content-Type'):
js = r.json()
else:
print('Response content is not in JSON format.')
js = 'spam'
回答4:
With your example as-is and no further understanding:
info = json.loads(json.dumps(userData))
will work.
There are a lot of posts on SO about python multi-line strings and JSON. Ideally you would not be loading a string from a string variable that way is the general comment you will see.
With some additional explanation, such as where does the data originate and in what format, I can provide additional assistance.
来源:https://stackoverflow.com/questions/51552765/json-decoder-jsondecodeerror-expecting-value-json-decoder-jsondecodeerror-e