How to add a key-value to JSON data retrieved from a file?
Your json_decoded
object is a Python dictionary; you can simply add your key to that, then re-encode and rewrite the file:
import json
with open(json_file) as json_file:
json_decoded = json.load(json_file)
json_decoded['ADDED_KEY'] = 'ADDED_VALUE'
with open(json_file, 'w') as json_file:
json.dump(json_decoded, json_file)
I used the open file objects as context managers here (with the with
statement) so Python automatically closes the file when done.
How to add a new key-value pair to each object in a JSON array
The only issue is with the placement of your print()
statement. It should be outside of the for
loop, and you should be printing entry['services']
rather than i
. This allows you to print all of updated entries at once, rather than one at a time.
y = {"pin":110096}
entry = json.loads(json_var)
for i in entry['services']:
i.update(y)
print(json.dumps(entry['services']))
This outputs:
[{"service_name": "stack1", "service_version": "1", "pin": 110096},
{"service_name": "stack2", "service_version": "2", "pin": 110096},
{"service_name": "stack3", "service_version": "3", "pin": 110096}]
How do I add a Key/Value in JSON with Python?
Use json module for that, code below shall give you the clue:
import json
data = json.load('path_to_json_file')
data['key'] = 'value'
json.dump('path_to_json_file', data)
Python JSON add Key-Value pair
You can do the following in order to manipulate the dict
the way you want:
for s in json_decoded['students']:
s['country'] = 'UK'
json_decoded['students']
is a list
of dictionaries that you can simply iterate and update in a loop. Now you can dump the entire object:
with open("output.json", 'w') as json_file:
json.dump(json_decoded, json_file)
Updating a python dictionary with specific key, value pairs from a json file
import json
with open('examine.json', 'r') as f:
json_inventory = json.load(f)
def addInventory(x):
try:
my_inventory[x] = json_inventory[x]
except Exception as e:
logging.info("User trying to add something that is not in the json")
def removeInventory(x):
try:
my_inventory.pop(x)
except Exception as e:
logging.info("User trying to remove something that is not in the inventory")
my_inventory = {}
x = 'egg'
addInventory(x) #add to your inventory
print(my_inventory)
x = 'stick'
addInventory(x) #add to your inventory again
print(my_inventory)
x = 'egg'
removeInventory(x) #remove from your inventory
print(my_inventory)
how to add value to key in json file using python
You cannot append new data it will break your json, you have to replace data. And dont focus on indent, its not necessary
try this:
import json
data={}
data['intents']=[]
data['intents'].append({
'tag': 'tag',
'patterns': 'patterns',
'response': 'response'
})
try:
with open('training.json', 'r') as training:
old_data = training.readlines()
if old_data:
old_data = json.loads(old_data[0])
for intents in data['intents']:
old_data['intents'].append(intents)
data = old_data
old_data = None
with open('training.json', 'w') as training:
json.dump(data, training)
except:
with open('training.json', 'w') as training:
json.dump(data, training)
Merge Json with same key value pairs
What you need is the dictionary function update(). Here's an example:
A = [{
"Uid": "40cc6103-1cf0-4735-b882-d14d32018e58",
"Id": "9e1a0057-4570-4a6e-8ff5-88b2facbaf4e",
"Details": {
"Name": "Kiran"
}
}, {
"Uid": "40cc6103-1cf0-4735-b882-d14d32018e58",
"Id": "9e1a0057-4570-4a6e-8ff5-88b2facbaf4e",
"Details": {
"Age": "24"
}
},
{
"Uid": "196f5865-e9fe-4847-86ae-97d0bf57b816",
"Id": "84909ecb-c92e-48a7-bcaa-d478bf3a9220",
"Details": {
"Name": "Shreyas"
}
}
]
B = []
def find(uid, id_):
for i, d in enumerate(B):
if d['Uid'] == uid and d['Id'] == id_:
return i
return -1
for d in A:
if (i := find(d['Uid'], d['Id'])) < 0:
B.append(d)
else:
B[i]['Details'].update(d['Details'])
print(B)
Prettyfied output:
[
{
"Uid": "40cc6103-1cf0-4735-b882-d14d32018e58",
"Id": "9e1a0057-4570-4a6e-8ff5-88b2facbaf4e",
"Details": {
"Name": "Kiran",
"Age": "24"
}
},
{
"Uid": "196f5865-e9fe-4847-86ae-97d0bf57b816",
"Id": "84909ecb-c92e-48a7-bcaa-d478bf3a9220",
"Details": {
"Name": "Shreyas"
}
}
]
Note:
This could be very inefficient if your API response contains very large numbers of dictionaries. You might need a completely different approach
Related Topics
Converting a Numpy Array into a Dict of Values Mapped to Rows
Keeping High Scores in a Text File
How to Stagger or Offset X-Axis Labels in Matplotlib
Find Records With Leading Zero in Python Pandas
Dice Rolling Simulator in Python
Pip Installation /Usr/Local/Opt/Python/Bin/Python2.7: Bad Interpreter: No Such File or Directory
Find the Longest Substring in Alphabetical Order
How to Append Two Bytes in Python
Django - How to Retrieve Data in Database in Dropdownlist