【问题标题】:Django python How to insert a json containing several objects in postgresqlDjango python如何在postgresql中插入一个包含多个对象的json
【发布时间】:2017-09-23 15:19:54
【问题描述】:

我想在我的数据库中插入一个包含多个出版物的 json。我想为每个出版物创建一个字段。目前我设法插入了一个包含单个出版物的 json,但是当我尝试使用两个时,这让我犯了一个错误:

脚本python:

fichier = open("result2.json","r")
filedata = json.load(fichier)
#for '{' in filedata:
   #print "ici un {"
prod = Production()
prod.cle = filedata.get("UT")
prod.titre = filedata.get("TITRE")
prod.publis = filedata
prod.maj = timezone.now()
prod.save()
fichier.close()

result2.json

{
   "UT": "WOS:123456",
   "TI": "firstpubli",
   "DT": "journal",
   "PY": "2016",
   "TITRE" :"firstpubli2016",
   "AU": "me, you"
 }

它有什么作用 [在此处输入图片说明][1]

现在,如果我在 result2.json 中放入 2 个出版物:

 {
   "UT": "WOS:123456",
   "TI": "firstpubli",
   "DT": "journal",
   "PY": "2016",
   "TITRE" :"firstpubli2016",
   "AU": "me, you"
 }   
 {
   "UT": "WOS:78910",
   "TI": "secondpubli",
   "DT": "journal",
   "PY": "2016",
   "TITRE" :"secondpubli2016",
   "AU": "me, you"
 }

当我运行 python 脚本插入数据时,我有这个错误

Traceback (most recent call last):
  File "test.py", line 45, in <module>
    filedata = json.load(fichier)
  File "/usr/lib/python2.7/json/__init__.py", line 291, in load
    **kw)
  File "/usr/lib/python2.7/json/__init__.py", line 339, in loads
    return _default_decoder.decode(s)
  File "/usr/lib/python2.7/json/decoder.py", line 367, in decode
    raise ValueError(errmsg("Extra data", s, end, len(s)))
ValueError: Extra data: line 12 column 2 - line 21 column 1 (char 143 - 282)

数据库中没有插入任何内容 当我的 json 中有 2 个作品时,我的目标是像这张图片一样,有 2 个作品 enter image description here

【问题讨论】:

  • 您不应该在 JSON 中的条目之间放置逗号吗?我的意思是,} , { 等等?

标签: python json django postgresql object


【解决方案1】:

您的文件不是 json 字符串。如果您想插入多个对象,则应使用用户列表。
您的文件应如下所示:
[{ "UT": "WOS:123456", "TI": "firstpubli", "DT": "journal", "PY": "2016", "TITRE" :"firstpubli2016", "AU": "me, you" }, { "UT": "WOS:78910", "TI": "secondpubli", "DT": "journal", "PY": "2016", "TITRE" :"secondpubli2016", "AU": "me, you" }]



你也应该像这样改变你的代码:
filedata = json.load(fichier) for f in filedata: //object insertion here

【讨论】:

    猜你喜欢
    • 2012-09-04
    • 1970-01-01
    • 2021-03-03
    • 2019-01-31
    • 1970-01-01
    • 2018-09-22
    • 2022-01-12
    • 1970-01-01
    相关资源
    最近更新 更多