json转换为双引号字符串python djang

2024-05-29 05:57:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个很奇怪的问题:

所以,我有一个简单的python字典,如下所示:

data={'Acoustics': {'Product Type': 'Acoustic Pod', 'Width [cm]': '1000', 'Noise Reduction Coefficient': '29 dB', 'Standards, Certification, and Documentation': 'PN EN-ISO 717-1:1999 ;  EN 13501 B, s1, d0', 'Material': 'MDF ;  Glass ;  Acoustic composite', 'Color': 'NCS ;  RAL', 'Installation Method': 'Own assembly ;  Installation by the manufacturer', 'Facing Material': 'MDF ;  Certified Paint', 'Type': 'Adjustable Ventilation ;  Motion Sensor ;  LED 6000K 2W ;  230V ;  RJ45 or USB Charger ;  Integrated seat and shelf'}}

我试图通过django将其保存到我的pgSQL数据库中(使用jsonb列),最后我得到了(注意开始和结尾处的双引号):

^{pr2}$

为了添加到我的数据库,我使用django表单,如下所示:

form_data={"cvar": data}
form = myform(form_data)
if form.is_valid():
    form.save()

现在,我有两个问题: [1] 如何避免上述情况?为什么它得到quoted?我只需传递一个表单数据来保存,它最终以字符串而不是json结束。 [2] 如果我有这样的引用json(不幸的是我现在有),我如何取消引用并以json的形式访问它(目前它是一个该死的字符串!)。在

谢谢。在


Tags: anddjango字符串form数据库json表单data
1条回答
网友
1楼 · 发布于 2024-05-29 05:57:26

没有MCVE showing the relevant code很难搞清楚。在

看起来您向数据库写入了一个字典,该字典转换为字符串,然后转换为JSON,而不是直接将字典转换为JSON。在

比如:

>>> import json
>>> a={'Acoustics': {'Product Type': 'Acoustic Pod', 'Width [cm]': '1000', 'Noise Reduction Coefficient': '29 dB', 'Standards, Certification, and Documentation': 'PN EN-ISO 717-1:1999 ;  EN 13501 B, s1, d0', 'Material': 'MDF ;  Glass ;  Acoustic composite', 'Color': 'NCS ;  RAL', 'Installation Method': 'Own assembly ;  Installation by the manufacturer', 'Facing Material': 'MDF ;  Certified Paint', 'Type': 'Adjustable Ventilation ;  Motion Sensor ;  LED 6000K 2W ;  230V ;  RJ45 or USB Charger ;  Integrated seat and shelf'}}

然后:

^{pr2}$

而不是:

^{3}$

如果已经将python字典表示形式作为来自某个外部数据源的字符串,则可以use ast.literal_eval() to turn it to a proper dict first

>>> the_dict=ast.literal_eval(the_data)
>>> the_json=json.dumps(the_dict)

或者,最好将数据源(例如web表单)更改为使用JSON格式而不是Python dict文本表示来交换数据。在

相关问题 更多 >

    热门问题