首页 > 解决方案 > 将字典附加到 JSON 文件

问题描述

我正在尝试将字典附加到已经有 2 个字典的 json 文件中。但它在同一个 json 文件中给了我初始文件和结果。我的代码如下。提前感谢人们。

import json
import os 

cwd = os.getcwd()
fp = cwd + '/xero_credentials.json'

def json_append():
    data_object = {
        "clientName": "Company Test",
        "clientId": "null",
        "clientSecret": "null",
        "redirect_url": "http://localhost:8080/callback",
        'scopes': "offline_access accounting.transactions.read accounting.journals.read",
        'refreshToken': "null"
        }

    with open(fp, 'r+') as json_file:
        data = json.load(json_file)
        data_dictionary = data['credentials']
        data_dictionary.append(data_object)
        json.dump(data, json_file, indent = 4, sort_keys=True)
    json_file.close()

# **********

json_append()

这是结果:

{
    "credentials": [
        {
            "clientName": "C1",
            "clientId": "null"
        },
        {
            "clientName": "C2",
            "clientId": "null"
        }
    ]
}
{
    "credentials": [
        {
            "clientName": "C1",
            "clientId": "null"
        },
        {
            "clientName": "C2",
            "clientId": "null"
        },
        {
            "clientName": "C3",
            "clientId": "null"
        }
    ]
}

标签: pythonjson

解决方案


就地更新文件很困难(除了一些特殊情况),因此通常必须首先将其全部内容读入内存,更新,然后用它来重写整个文件。

这就是我的意思:

import json
import os

cwd = os.getcwd()
fp = cwd + '/xero_credentials.json'

def json_append():
    data_object = {
        "clientName": "Company Test",
        "clientId": "null",
        "clientSecret": "null",
        "redirect_url": "http://localhost:8080/callback",
        'scopes': "offline_access accounting.transactions.read accounting.journals.read",
        'refreshToken': "null"
        }

    # Read the entire file.
    with open(fp, 'r') as json_file:
        data = json.load(json_file)

    # Update the data read.
    credentials = data['credentials']
    credentials.append(data_object)

    # Update the file by rewriting it.
    with open(fp, 'w') as json_file:
        json.dump(data, json_file, indent=4, sort_keys=True)


json_append()

更新后的文件:

{
    "credentials": [
        {
            "clientId": "null",
            "clientName": "C1"
        },
        {
            "clientId": "null",
            "clientName": "C2"
        },
        {
            "clientId": "null",
            "clientName": "Company Test",
            "clientSecret": "null",
            "redirect_url": "http://localhost:8080/callback",
            "refreshToken": "null",
            "scopes": "offline_access accounting.transactions.read accounting.journals.read"
        }
    ]
}

推荐阅读