【发布时间】:2016-03-15 02:09:52
【问题描述】:
问题在于存在多个修订 ID,并且无论存在多少修订,它都只需要一个修订 ID。将字典与 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 字典中的键必须是唯一的。换句话说,您不能有两个或多个具有相同键的项目。我建议您将“修订”设为
dicts 的list,并可能将其重命名为“修订”。或者,您可以使用“revision0”、“revision1”等键,但使用起来并不愉快。 -
实际上,我的第二个建议可能是更好的选择,因为您无法控制 JSON 的创建。正如 Paul Gowder 所提到的,您可以在将 JSON 文本传递给 Python 的 JSON 解析器之前使用正则表达式替换来修改它。如果您需要帮助进行编码,建议将一些示例 JSON 数据作为文本而不是链接图像发布。
-
这个问题展示了如何使用
json模块解析此类文件:Python json parser allow duplicate keys。 -
你的意思是我应该阅读每一行,如果是修订,则为每个对象附加修订1、修订2等?
-
是的,这是我之前的建议,但是看看我刚刚链接到的问题,它显示了一个更好的方法。
标签: python json dictionary wikipedia dump