Posts: 42
Threads: 22
Joined: Oct 2021
Dec-22-2021, 04:25 PM
(This post was last modified: Dec-22-2021, 04:25 PM by 3lnyn0.)
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
}
]
Posts: 4,790
Threads: 76
Joined: Jan 2018
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)
Posts: 42
Threads: 22
Joined: Oct 2021
(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
Posts: 1,583
Threads: 3
Joined: Mar 2020
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.
Posts: 42
Threads: 22
Joined: Oct 2021
(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)
Posts: 4,790
Threads: 76
Joined: Jan 2018
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)
Posts: 1,094
Threads: 143
Joined: Jul 2017
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
"""
|