JSON字典重复自动消除
问题描述:
问题是存在多个版本ID,无论有多少修订版本存在,它只需要一个版本ID。与JSON一起使用字典。JSON字典重复自动消除
需要获取所有存在的修订标签。
数据结构:Structure of the JSON file
Code:
#Defining a blank dictionary
data = {}
#File Loading Command
with open(path+filename,encoding="iso-8859-1") as file:
data = json.load(file)
#Defining the Base Date to subtract from
basedate = date(2006, 1, 1)
#Number of Objects in JSON
for count in range(140):
#If there is any data in that then do the following
if(data[count]):
for each_item in data[count]:
#If the item is revision
if each_item == "revision":
#This is where the problem lies since it always only fetches one revision
time = data[count]["revision"]["timestamp"]
currentdate = date(int(time[0:4]),int(time[5:7]),int(time[8:10]))
#Calculating Days
delta = currentdate - basedate
print(data[count]["title"] + ": " +str(delta))
==================================编辑1 ================================
这里显示的JSON相当大,因此:https://api.myjson.com/bins/4sxm3
答
Python字典就像其他语言的哈希表,键是唯一的。看起来您在JSON对象中有多个“修订”条目,这就是问题所在。关于JSON中非唯一键的不可见性,请参见prior SO。可能最好的做法是重新格式化JSON,以便为每个ID制作修订列表;不知道如何做到这一点没有像正则表达式替换的东西hackish ...
另外,你不需要预先初始化一个字典,Python标准库JSON模块将足够聪明,把JSON对象转换为字典在其自己的。
Python字典中的键**必须是唯一的。换句话说,你不能有两个或更多的项目具有相同的密钥。我建议你将“修订版”作为'dict'的'list',并且可能将其重命名为“修订版”。或者,你可以拥有诸如“revision0”,“revision1”等的键,但这并不令人愉快。 –
其实,我的第二个建议可能是更好的选择,因为你无法控制JSON的创建。正如Paul Gowder所提到的,您可以在通过Python的JSON解析器之前使用regex替换来修改JSON文本。如果您需要编码的帮助,建议将一些示例JSON数据作为文本发布,而不是作为链接图像。 –
这个问题显示了如何使用'json'模块解析这些文件:[Python json解析器允许重复键](http://*.com/q/29321677/4014959)。 –