在python中编写JSON数据.格式



我有一个将json数据写入文件的方法。标题是基于书籍的,数据是书籍的出版商、日期、作者等。如果我想添加一本书,这种方法很好。

代码

import json
def createJson(title,firstName,lastName,date,pageCount,publisher):
print "n*** Inside createJson method for " + title  + "***n";
data = {} 
data[title] = []
data[title].append({
'firstName:', firstName,
'lastName:', lastName,
'date:', date,
'pageCount:', pageCount,
'publisher:', publisher
})
with open('data.json','a') as outfile:
json.dump(data,outfile , default = set_default)
def set_default(obj):   
if isinstance(obj,set):
return list(obj)

if __name__ == '__main__':  
createJson("stephen-king-it","stephen","king","1971","233","Viking Press") 

带有一本书/一个方法调用的JSON文件

{
"stephen-king-it": [
["pageCount:233", "publisher:Viking Press", "firstName:stephen", "date:1971", "lastName:king"]
]
}

但是,如果我多次调用该方法,从而向json文件中添加更多书籍数据。格式完全错误。例如,如果我简单地用的主方法调用该方法两次

if __name__ == '__main__':  
createJson("stephen-king-it","stephen","king","1971","233","Viking Press")        
createJson("william-golding-lord of the flies","william","golding","1944","134","Penguin Books") 

我的JSON文件看起来像

{
"stephen-king-it": [
["pageCount:233", "publisher:Viking Press", "firstName:stephen", "date:1971", "lastName:king"]
]
}  {
"william-golding-lord of the flies": [
["pageCount:134", "publisher:Penguin Books", "firstName:william","lastName:golding", "date:1944"]
]
}

这显然是错误的。有没有一个简单的修复程序可以编辑我的方法来生成正确的JSON格式?我在网上看到了许多关于将json数据放入python的简单示例。但当我在JSONLint.com上查看时,他们都给了我格式错误。我一直在绞尽脑汁解决这个问题,并编辑文件以使其正确。然而,我所有的努力都无济于事。感谢您的帮助。非常感谢。

简单地将新对象附加到文件中并不能创建有效的JSON。您需要在顶级对象中添加新数据,然后重写整个文件。

这应该有效:

def createJson(title,firstName,lastName,date,pageCount,publisher):
print "n*** Inside createJson method for " + title  + "***n";
# Load any existing json data,
# or create an empty object if the file is not found,
# or is empty
try:
with open('data.json') as infile:
data = json.load(infile)
except FileNotFoundError:
data = {}
if not data:
data = {} 
data[title] = []
data[title].append({
'firstName:', firstName,
'lastName:', lastName,
'date:', date,
'pageCount:', pageCount,
'publisher:', publisher
})
with open('data.json','w') as outfile:
json.dump(data,outfile , default = set_default)

JSON可以是数组,也可以是字典。在您的案例中,JSON有两个对象,一个具有关键字stephen-king-it,另一个具有william-golding-lord of the flies。它们中的任何一个单独使用都可以,但将它们组合在一起的方式是无效的。

使用阵列可以做到这一点:

[
{ "stephen-king-it": [] },
{ "william-golding-lord of the flies": [] }
]

或者字典样式的格式(我推荐这样(:

{ 
"stephen-king-it": [],
"william-golding-lord of the flies": []
}

此外,您所附加的数据看起来应该格式化为字典中的键值对(这将是理想的(。您需要将其更改为:

data[title].append({
'firstName': firstName,
'lastName': lastName,
'date': date,
'pageCount': pageCount,
'publisher': publisher
})

最新更新