[英]Why can I not deserialise a JSON string with single quotes in Python?
I am using json to deserialize a string that is received from my MySQL database such that the resulting object is a dictionary.我正在使用 json 反序列化从我的 MySQL 数据库接收到的字符串,以便生成的对象是一个字典。
This is the code:这是代码:
sql.cursorobj.execute("SELECT * FROM timetableevents")
for record in sql.cursorobj.fetchall():
print(record)
obj= record['btnobject']
detailsdict[obj]=json.loads(record['details']) #I am facing an error here
The error I am getting is:我得到的错误是:
{'btnobject': 'btnobject1', 'details': "{'sno':[], 'time':[], 'events':[]}"}
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\veeru\Python 3.9.2\lib\tkinter\__init__.py", line 1892, in __call__
return self.func(*args)
File "c:\Users\veeru\OneDrive\Visual Studio\Timetable\TimeTable.py", line 186, in <lambda>
addtaskbtn.configure(command=lambda x=(btnobj, tableframe): ae.addtaskbtnclick(x[0], x[1]))
File "c:\Users\veeru\OneDrive\Visual Studio\Timetable\addevent.py", line 33, in addtaskbtnclick
updateglobalvalues(btnobj)
File "c:\Users\veeru\OneDrive\Visual Studio\Timetable\addevent.py", line 22, in updateglobalvalues
detailsdict[obj]=json.loads(f"{record['details']}")
File "C:\Users\veeru\Python 3.9.2\lib\json\__init__.py", line 346, in loads
return _default_decoder.decode(s)
File "C:\Users\veeru\Python 3.9.2\lib\json\decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "C:\Users\veeru\Python 3.9.2\lib\json\decoder.py", line 353, in raw_decode
obj, end = self.scan_once(s, idx)
json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 2 (char 1)
The last line in the above error code is of most importance ig.上述错误代码中的最后一行是最重要的 ig。
I have tried enclosing the record['details']
in double quotes explicitly I have also used fstrings
like: json.loads(f"{record['details']}")
我已经尝试将record['details']
明确地用双引号括起来我还使用了fstrings
例如: json.loads(f"{record['details']}")
**NOTE: ** **笔记: **
Keep in mind that json.loads(record['details'])
worked previously, but after I changed my database, it stopped working.请记住, json.loads(record['details'])
以前可以工作,但是在我更改数据库后,它停止工作。
if you try to load如果您尝试加载
print(json.loads('{"sno":[], "time":[], "events":[]}'))
it will give you no error cause key is in double qoute, and you'll get the result它不会给你任何错误,因为键是双 qoute,你会得到结果
{'sno': [], 'time': [], 'events': []}
but if you cant change the output then try json.dumps
first但如果你不能改变输出,那么首先尝试json.dumps
print(json.dumps("{'sno':[], 'time':[], 'events':[]}"))
this will give you这会给你
'"{\'sno\':[], \'time\':[], \'events\':[]}"'
Your JSON string is invalid.您的 JSON 字符串无效。
A string is a sequence of zero or more Unicode characters, wrapped in double quotes , using backslash escapes.字符串是零个或多个 Unicode 字符的序列,用双引号括起来,使用反斜杠转义。
It has single quotes while JSON strings should have double quotes to be valid.它有单引号,而 JSON 字符串应该有双引号才有效。
You don't really have the option to mass replace the quotation marks from the database so use json.dumps
before loading the JSON to convert the quotation marks.您实际上无法从数据库中批量替换引号,因此json.dumps
在加载 JSON 之前使用json.dumps
来转换引号。
Try this:尝试这个:
detailsdict[obj]=json.loads(json.dumps(record['details']))
Or use ast.literal_eval
:或使用ast.literal_eval
:
import ast
`detailsdict[obj]=json.loads(ast.literal_eval(record['details']))`
You have single quotes in our string and hence you get this error.您在我们的字符串中有单引号,因此您会收到此错误。 What you can do is replace '
with "
and then do a json.loads
as below:您可以做的是将'
替换为"
然后执行json.loads
如下:
sql.cursorobj.execute("SELECT * FROM timetableevents")
for record in sql.cursorobj.fetchall():
print(record)
obj= record['btnobject']
# Replace ' with "
details = record['details'].replace("'", '"')
detailsdict[obj]=json.loads(details) #I am facing an error here
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.