简体   繁体   English

为什么我不能在 Python 中反序列化带有单引号的 JSON 字符串?

[英]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 字符串无效。

From json.org :来自json.org

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.

相关问题 使用python,即使字符串使用单引号,我如何检查字符串是否为有效的json对象? - Using python, how can I check if a string is a valid json object, even if the string uses single quotes? 我如何在python regex中找到单引号内的字符串 - How can i find the string inside single quotes in python regex 如何将单引号传递给 python 中的 json 字符串? - How to pass single quotes to json string in python? Python如何将单引号转换为双引号以格式化为json字符串 - Python how convert single quotes to double quotes to format as json string JSON string Python中用两个单引号替换单引号 - JSON string Replace single quote with two single quotes in Python 如何在 python 数组中用双引号替换单引号而不替换 json 值中的单引号? - How do I replace single quotes with double quotes in a python array without replacing the single quotes in the json values? 如何判断具有空字符串值的 python 字符串变量在初始化时是使用单引号还是双引号? - How can i tell if a python string variable with an empty string value is using single quotes or double quotes at init time? Python JSON将单引号更改为双引号,不考虑字符串内引号 - Python JSON change single quotes to double quotes leave in-string quotes alone 为什么python在单引号前在字符串中加上“ \\\\” - Why python is putting “\\” in my string before single quotes 如何创建包含单引号和双引号 python 的字符串? - How can I create a string that contains both single and double quotes python?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM