【发布时间】:2019-04-15 14:45:46
【问题描述】:
我有一个很奇怪的问题:
所以,我在 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 列),但我最终得到了(注意开头和结尾的双引号):
"{'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 表单,如下所示:
form_data={"cvar": data}
form = myform(form_data)
if form.is_valid():
form.save()
所以,现在,我有两个问题:
[1] 如何避免上述情况?为什么会得到quoted?我只是传递一个表单数据来保存,它以某种方式以字符串而不是 json 结尾。
[2] 如果我有这样引用的 json(不幸的是我现在这样做了),我如何取消引用并将其作为 json 访问(目前它是一个该死的字符串!)。
谢谢。
【问题讨论】:
-
如果你想在这里找到帮助,你应该展示你的示例代码。
-
您将字典保存为 Json 字符串。如果要将json字符串转换为json对象,可以使用
json.loads -
@BearBrown:我现在添加了这个,但它是普通的香草形式..
-
@wendelbsilva:这绝对不正确。你可以自己试试。
-
请显示您的模型和表单定义。请注意,您将字符串称为与 JSON 不同的事物会混淆事物; JSON是一种字符串格式。但是,该字符串实际上不是有效的 JSON,所以发生了一些奇怪的事情。
标签: python json django postgresql