jumpman8947
jumpman8947

Reputation: 279

Copy JSON file then append it and a dictionary to another JSON file

I have an existing JSON file, a new JSON file to be made, and an existing Python dictionary. What I'm trying to do is copy over the data in my existing JSON file to my new JSON file and then append my dictionary to the new JSON file.

mydict = {'a':1, 'b':2, 'c':3}

My JSON file looks like a Python dictionary:

{'hi': 4, 'bye' : 5, 'hello' : 6}

So far, I have:

with open('existing.json', 'r') as old, open ('recent.json', 'a') as new:
  #This is where i get stuck on how to copy over the contents of existing.json, and how to append mydict as well.

I want the end result to be one dictionary containing the contents of existing.json and mydict. Also if I turn this into a function I want to be able to always keep the contents that are already in recent.json and just append a new line of data.

Upvotes: 0

Views: 2217

Answers (2)

Dušan Maďar
Dušan Maďar

Reputation: 9889

Load your existing JSON to a dictionary, then combine this loaded data with your dictionary and save combined data as JSON.

import json


def combine_json_with_dict(input_json, dictionary, output_json='recent.json'):
    with open(input_json) as data_file:
        existing_data = json.load(data_file)

    combined = dict(existing_data, **dictionary)

    with open(output_json, 'w') as data_file:
        json.dump(combined, data_file)

Upvotes: 0

rtemperv
rtemperv

Reputation: 675

You can load update and write back the file like this:

import json

mydict = {'a':1, 'b':2, 'c':3}

data = json.load(open('existing.json'))
data.update(mydict)
json.dump(data, open('recent.json', "w"))

Upvotes: 2

Related Questions