【问题标题】:JSON Dictionary Duplicate Automatically Eliminated [duplicate]JSON字典重复自动消除[重复]
【发布时间】: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


【解决方案1】:

Python 字典就像其他语言中的哈希表,键是唯一的。看起来您在 JSON 对象中有多个“修订”条目,这就是问题所在。请参阅此prior SO,了解 JSON 中非唯一键的不可取性。最好的办法可能是重新格式化 JSON 以列出每个 ID 的修订列表;不知道如何在没有正则表达式替换之类的黑客的情况下做到这一点......

此外,您无需预先初始化字典,Python 标准库 JSON 模块将非常智能,可以自行将 JSON 对象转换为字典。

【讨论】:

    猜你喜欢
    • 2018-08-13
    • 1970-01-01
    • 1970-01-01
    • 2016-03-05
    • 2020-06-14
    • 2019-09-26
    • 1970-01-01
    • 2020-03-03
    • 2011-10-28
    相关资源
    最近更新 更多