Python Forum
add dictionarie in json file
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
add dictionarie in json file
#1
Hi!
Help me with an advise.
How to add multiple dictionary in a JSON file I want to add 1 or 2 dictionaries once and after a while to add 1 or 2 or 3 dictionaries in same JSON file.

import json

dict1 = {'a': 1, 'b': 1}
dict2 = {'c': 2, 'd': 2}
dict3 = {'e': 3, 'f': 3}
list1 = []
list1.append(dict1)
list1.append(dict2)
with open('testjson_dict.json', 'a', encoding='utf-8') as f:
    json.dump(list1, f)
I added dict1 to list1, then I added dict2 to list 1 and then I ran the code.

list1.append(dict3)
with open('testjson_dict.json', 'a', encoding='utf-8') as f:
    json.dump(list1, f)
Then I added dict3 to list1 and then I ran the code.
For dict3 created a new list, did not add it to the list of dictionaries already in the json file, put it in a new list. I want to put it in the same list for everyone if I add a new dictionary and run the code.
And I used append for the first time, when the json file was empty, I don't know how to write the code to use write when the file is empty and when the file has something in it to use append.


Output:
[ { "a": 1, "b": 1 }, { "c": 2, "d": 2 } ][ { "e": 3, "f": 3 } ]
Reply
#2
You could load the list before appending
with open('testjson_dict.json') as ifh:
    list1 = json.load(ifh)
dict3 = {'e': 3, 'f': 3}
list1.append(dict3)
with open('testjson_dict.json', 'w') as f:
    json.dump(list1, f)
Reply
#3
(Dec-22-2021, 04:35 PM)Gribouillis Wrote: You could load the list before appending
with open('testjson_dict.json') as ifh:
    list1 = json.load(ifh)
dict3 = {'e': 3, 'f': 3}
list1.append(dict3)
with open('testjson_dict.json', 'w') as f:
    json.dump(list1, f)

it's not working
Error:
list1 = json.load(ifh) File "C:......\json\__init__.py", line 293, in load return loads(fp.read(), io.UnsupportedOperation: not readable
Reply
#4
Please show all the code as well.

The post you are replying to has the initial open specified as:
with open('testjson_dict.json') as ifh:
which uses the default open mode of "read". Your error message suggests that you are using a mode "w" (or "a"). You've opened the file for writing only and have asked the json method to read from it.
Reply
#5
(Dec-22-2021, 05:08 PM)bowlofred Wrote: Please show all the code as well.

The post you are replying to has the initial open specified as:
with open('testjson_dict.json') as ifh:
which uses the default open mode of "read". Your error message suggests that you are using a mode "w" (or "a"). You've opened the file for writing only and have asked the json method to read from it.


it has
import json

dict1 = {'a': 1, 'b': 1}
dict2 = {'c': 2, 'd': 2}
dict3 = {'e': 3, 'f': 3}

list1 = []

list1.append(dict1)
list1.append(dict2)

with open('testjson_dict.json', 'w') as ifh:
    list1 = json.load(ifh)

dict3 = {'e': 3, 'f': 3}
list1.append(dict3)

with open('testjson_dict.json', 'w') as f:
    json.dump(list1, f)
Reply
#6
Here is what I meant
import json
 
dict1 = {'a': 1, 'b': 1}
dict2 = {'c': 2, 'd': 2}
 
list1 = []
 
list1.append(dict1)
list1.append(dict2)

with open('testjson_dict.json', 'w') as f:
    list1 = json.dump(list1, f)

#  later...
with open('testjson_dict.json') as ifh:
    list1 = json.load(ifh)

dict3 = {'e': 3, 'f': 3}
list1.append(dict3)
 
with open('testjson_dict.json', 'w') as f:
    json.dump(list1, f)
Reply
#7
myApp() for collecting client data, just copy and paste in your shell.

Can of course be improved on!

def myApp():    
    # get the modules
    import json
    from pathlib import Path

    """
    When you load the .json file with data = json.load(f) you have a dictionary of dictionaries
    Then you can do all the things Python dictionaries can do.
    """

    mypath = '/home/pedro/temp/clients_data_json.json'
    
    # check if the json you want exists
    chk_file = Path(mypath) 
    if chk_file.is_file():
        print(mypath, 'exists, so open it ... \n\n')
        with open(mypath) as f:
            data = json.load(f)
    else:
        print("File does not exist, so make data an empty dictionary!\n\n")
        data = {}     

    
    # collect data
    # this is a list of things we need to know about each client
    
    collect_data = ['first name(s)', 'surname','telephone','email']

    # a function to collect our data
    # this function returns a dictionary with client data
    
    def get_client_data():
        client_dict = {}
        print('First get client_id and check it ... ')
        client_id = input('Please enter the client_id: ')
        # check if this key exists, if so, don't accept it
        # the product_id must be unique, so use the dict.get(key) method
        while not data.get(client_id) == None:
            print('This client id is already in use, try again.')
            client_id = input('Please enter the client_id: \n\n')
        
        # now we have a unique client_id
        print('Please now enter the details for the client with client id', client_id)
        for info in collect_data:            
            client_dict[info] = input(f'Please enter the {info}: ')
        data[client_id] = client_dict
        

    replies = ['yes', 'no']
    reply = 'X'
    # still need a way to keep the product ids unique!!
    while not reply in replies:    
        print('Do you want to enter 1 or more new clients?')
        reply = input('Enter yes to continue, enter no to stop ')
        if reply == 'yes':
            answers = get_client_data()
            reply = 'maybe'
        elif reply == 'no':
            break

    for key in data.keys():
        print('Client ID is', key)
        print('Client name is:', data[key]['first name(s)'], data[key]['surname'])
        print('Client telephone is:', data[key]['telephone'])
        
    
    # save the data dictionary as a .json file
    # USE YOUR PATH    
    # open 'w' and overwrite the existing file
    print('Now saving the client data, run myApp() again to add more clients later ... ')
    with open(mypath, 'w') as json_file:
        json.dump(data, json_file)
    print('data saved to', mypath)

    # open the file you just saved in mypath to inspect it
    # USE YOUR PATH
    print('Now reopening', mypath, 'to have a look at the data ... ')
    with open(mypath) as f:
      data = json.load(f)

    print('data is ' + str(len(data)) + ' entries long')

    # look at the content of '/home/pedro/temp/clients_data_json.json'

    for item in data.items():
        print(json.dumps(item, indent = 4, sort_keys=True))

    print('All done, byebye!')

    """
    You can open and append to this json file any time
    """
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  JSON File - extract only the data in a nested array for CSV file shwfgd 2 1,085 Aug-26-2024, 10:14 PM
Last Post: shwfgd
  encrypt data in json file help jacksfrustration 1 2,244 Mar-28-2024, 05:16 PM
Last Post: deanhystad
  parse json field from csv file lebossejames 4 2,034 Nov-14-2023, 11:34 PM
Last Post: snippsat
  Python Script to convert Json to CSV file chvsnarayana 8 4,755 Apr-26-2023, 10:31 PM
Last Post: DeaD_EyE
  Loop through json file and reset values [SOLVED] AlphaInc 2 5,491 Apr-06-2023, 11:15 AM
Last Post: AlphaInc
  Converting a json file to a dataframe with rows and columns eyavuz21 13 14,084 Jan-29-2023, 03:59 PM
Last Post: eyavuz21
  validate large json file with millions of records in batches herobpv 3 2,216 Dec-10-2022, 10:36 PM
Last Post: bowlofred
  Writing to json file ebolisa 1 1,709 Jul-17-2022, 04:51 PM
Last Post: deanhystad
  Trying to parse only 3 key values from json file cubangt 8 6,661 Jul-16-2022, 02:05 PM
Last Post: deanhystad
  Initializing, reading and updating a large JSON file medatib531 0 2,797 Mar-10-2022, 07:58 PM
Last Post: medatib531

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020