I can’t add data to JSON file ( read/write (I/O Input)).
its data type is : STR
I don’t want it and I want data type : DICT
with open("users.json","r") as myfile :
result = myfile.read()
print(type(result)) # STR but I want DICT
Please explain to me.
2
Try using the json
module from the standard library. Say you have a users.json
file with the following contents:
{
"user1": {
"name": "Alice",
"age": 25
},
"user2": {
"name": "Bob",
"age": 28
}
}
You can read it into a dictionary using json.load
and use json.dump
to write it back to a file after you modify it:
import json
with open('users.json', 'r') as myfile:
result = json.load(myfile)
print(f'{result = }')
print(f'{type(result) = }')
result['user3'] = {'name': 'Chuck', 'age': 30}
with open('new_users.json', 'w') as myfile:
json.dump(result, myfile, indent=4)
Output:
result = {'user1': {'name': 'Alice', 'age': 25}, 'user2': {'name': 'Bob', 'age': 28}, 'user3': {'name': 'Chuck', 'age': 30}}
type(result) = <class 'dict'>
✨ Newly created ✨ new_users.json
:
{
"user1": {
"name": "Alice",
"age": 25
},
"user2": {
"name": "Bob",
"age": 28
},
"user3": {
"name": "Chuck",
"age": 30
}
}