Python如何更新JSON文件

时间:2017-01-18 17:00:24

标签: python json python-3.x

我有一个JSON文件,如下所示:

{
    "files": [
        {
            "nameandpath": "/home/test/File1.zip",
            "MD5": "e226664e39dc82749d05d07d6c3078b9",
            "name": "File1"
        },
        {
            "nameandpath": "/home/test/File2.zip",
            "MD5": "dbb11b2095c952ff1d4b284523d3085f",
            "name": "File2"
        }
    ]
}

当条件为真时,我希望仅更新2行nameandpath和MD5。 条件是如果测试的文件存在于JSON文件中:我将更新该行,否则我将添加具有其3个值的文件。

{
    "files": [
        {
            "nameandpath": "/home/test/File1.zip",
            "MD5": "e226664e39dc82749d05d07d6c3078b9",
            "name": "File1"
        },
        {
            "nameandpath": "/home/test/File2.zip",
            "MD5": "dbb11b2095c952ff1d4b284523d3085f",
            "name": "File2"
        }
        # block added because the file tested wasn't present in json file
        {
            "nameandpath": "/home/test/File3.zip",
            "MD5": "dbb11b2095c952ff1d4b284523d3085f",
            "name": "File3"
        }
    ]
}

我无法更新现有的线路 我还没有能够测试添加新线路。

你能帮帮我吗? 我该怎么办?

到目前为止我的代码:

# getting file name
# getting MD5 of the file

jsonfile = "/home/test/filesliste.json"

 with open(jasonfile, "r+") as json_file:
        data = json.load(json_file)
        for tp in data['files']:
            if tp['name'] == name:
                if tp['MD5'] == fileMD5:
                    print("same MD5")
                    # adding this file to json file
                else:
                    print("NOT THE same MD5")
                    # updating the file info into json file

1 个答案:

答案 0 :(得分:0)

我不清楚你到底在做什么。这是我构建代码的方式,也许这会有所帮助:

jsonfile = "/home/test/filesliste.json"

# read json file
with open(jsonfile) as f:
    data = json.load(f)

# find index of file or -1 if not found
index = -1
for i, tp in enumerate(data['files']):
    if tp['name'] == name and tp['MD5'] == fileMD5:
        index = i
        break

# update data
# we're lazy and just delete the old file info, then re-add it
if index >= 0:
    del data['files'][index]

tp = {
    "name": ...,
    "nameandpath": ...,
    "MD5": ...,
}
data.append(tp)

# write data back to file
with open(jsonfile) as f:
    # json.dump or something like that

MD5

不应再使用MD5,因为它被认为是破碎的。如果可能,您应该使用类似但更安全的SHA-2或SHA-3替换它。