简体   繁体   中英

Append Dictionary to JSON file

I am trying to append a dictionary to a json file with already 2 dictionaries. But it is giving me the initial file and the results all together in the same json file. My code is as below. Thanks in advance people.

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()

This is the result:

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

It is difficult to update a file in-place (except for some special cases), so generally one often has to first read its entire contents into memory, update that, and then use it to rewrite the entire file.

Here's what I mean:

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()

Updated file:

{
    "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"
        }
    ]
}

Edit: Misunderstood the question.

The problem is taht you are using "r+" mode when opening the file. That means that you will be able to read and append but not edit, which is what you are trying to do.

Just use with open(fp, 'w') .

Also, you don't need to explicitly close the file. Context managers, such as with do that automatically once you leave their scope.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM