-1

I want to export certain variables to an existing JSON file, but I don't know how to add something to an existing dictionary, I also have dictionaries that already have the variables but I want to update their values, how do I do this?

The python code that I have now makes a new dictionary, which is not what I want, any help is appreciated

Python file:

export_dict = {'salary':salary_int,'interest':interest_int}

with open(f'{os.getcwd()}/Data/Insta-database.json','r') as inputfile:
    file = json.load(inputfile)
    file['data'].append(export_dict)

with open(f'{os.getcwd()}/Data/Insta-database.json', 'w') as outfile: 
    json.dump(file, outfile, indent = 4)

JSON file:

{
    "data": [
        {
            "name": "quesa",
            "surname": "fum", // I want to add the salary and interest variables beneath these
        },
        {
            "name": "hau",
            "surname": "guygo",
            "salary": "213,324", // I want to update these values
            "interest": "5%", // I want to update these values
        },
        {
            "name": "ksmair",
            "surname": "bree",
            "salary": "943,229", // I want to update these values
            "interest": "15%", // I want to update these values
        }
    ]
}
tripleee
  • 175,061
  • 34
  • 275
  • 318
BuddyPal
  • 61
  • 1
  • 6
  • I think you are using either to work python3 or python2 cuz you have used both tags, answers should be in both, do you want answer in both python2 and python3? – imxitiz Aug 01 '21 at 11:26
  • I removed both tags. In this day and age, expect everyone to have moved on to Python 3. Unless you are *specifically* asking about how to solve a cross-version compatibility problem (in which case your question should obviously describe that problem) you should not mix the [tag:python-2.7] and [tag:python-3.x] tags. – tripleee Aug 01 '21 at 12:19

1 Answers1

2

Like you discovered yourself, your code adds a new key to the top-level dictionary. If there are multiple places where you want to update the values, you need to modify each of them separately, perhaps via a loop.

with open('Data/Insta-database.json', 'r') as inputfile:
    file = json.load(inputfile)

for elem in file['data']:
    elem.update(export_dict)

with open('Data/Insta-database.json', 'w') as outfile: 
    json.dump(file, outfile, indent = 4)

Demo: https://ideone.com/yUKnrJ

Notice also how the os.getcwd() call is not necessary; the operating system by definition resolves relative file names from the current working directory. For details, see What exactly is current working directory?

tripleee
  • 175,061
  • 34
  • 275
  • 318