How to update a value in nested JSON file using python?
Since you use json.load
to load the file back into a Python object via the default conversion table, you should get a dictonary in your case.
So you should be able to edit the data normally like in a dict, in your case:
json_data["students"]["2"]["marks"]["english"] = updated_marks
EDIT:
Since you want to make the call based on the path_to_english_marks list, you can do something like mentioned here from jjp.
from functools import reduce
from operator import getitem
def set_nested_item(dataDict, mapList, val):
"""Set item in nested dictionary"""
reduce(getitem, mapList[:-1], dataDict)[mapList[-1]] = val
return dataDict
key_lst = ["key1", "key2", "key3"]
value = "my_value"
d = {"key1": {"key2": {"key3": "some_value"}}}
d = set_nested_item(d, key_lst, value)
print(d)
# {'key1': {'key2': {'key3': 'my_value'}}}
How to update json object with dictionary in python
I think you need to use an iterator to the items:
updates = {"westbuilt": "4232", "Northbound": "5556"}
r = requests.get(url="*URL*")
file = r.json()
items = iter(updates.items())
try:
for i in file['collection']:
if 'corporateIdentificationNumber' in i:
d = next(items)
i['name'] = d[0]
i["corporateIdentificationNumber"] = d[1]
except StopIteration:
pass
print(file)
update json property value using for loop in python?
The straight forward way:
for obj in json:
if obj['id'] == 2:
obj['name'] = 'something'
Objects are mutable, so you're directly mutating the object here. This is the simplest way. The typical Javascript equivalent would be:
json.forEach(obj => {
if (obj.id == 2) {
obj.name = 'something';
}
});
The slightly more condensed version:
for obj in (o for o in json if o['id'] == 2):
obj['name'] = 'something'
This inlines a generator expression which pre-filters the objects to loop over. Alternatively:
for obj in filter(lambda o: o['id'] == 2, json):
obj['name'] = 'something'
Somewhat equivalent to:
json.filter(o => o.id == 2).forEach(obj => obj.name = 'something')
The even more condensed version:
json = [{**obj, 'name': 'something' if obj['id'] == 2 else obj['name']} for obj in json]
This is a list comprehension which builds a new object and new list, somewhat equivalent to:
json = json.map(o => ({...obj, name: obj.id == 2 ? 'something' : obj.name}))
You decide what you find most readable…
Update Json value in python
From the structure you mentioned, the title
key that you need to modify is more nested than what you are providing with.
You need to make the following change:
prev_date = datetime.date.today()-datetime.timedelta(1)
new_date = str(prev_date.isoformat())
res = {
"requests": [
{
"addSheet": {
"properties": {
"title": ""
}
}
}
]
}
res['requests'][0]['addSheet']['properties']['title'] = new_date
print (res)
Where:
'requests'
value is alist
0
is the first item in the list (and the only item)'addSheet'
is the key in the dictionary that is the value of the item in the list in the0
index'properties'
is the key in the above dictionary'title'
is the key in the above dictonary, and the one you need upon your request
Append data using update method to json object just add last loop item using python
update()
is used to update the dictionary. If your dictionary already has a value for the specified key, it will get overwritten. Otherwise, a new key/value pair will be added.
Here you want to create a list of all dates less than since
. So, you need to have a list
for ch
key in your dictionary:
plot_material = {}
# Notice the square brackets
plot_material['ch'] = [china['data'][start_time]]
And, then you will just .append()
the new values:
plot_material['ch'].append(china['data'][date])
Related Topics
How to Make a Tkinter Label Background Transparent
Regular Expression: Match Everything After a Particular Word
What Do Numbers Starting With 0 Mean in Python
Checking If Particular Value (In Cell) Is Nan in Pandas Dataframe Not Working Using Ix or Iloc
How to Run Linux Terminal Command in Python in New Terminal
Convert Images from [-1; 1] to [0; 255]
How to Drop Rows from Pandas Data Frame That Contains a Particular String in a Particular Column
How to Remove Parentheses from a String
How to Remove All Characters Before a Specific Character in Python
Python Pandas Dataframe Get All Combinations of Column Values
How to Install Pip for a Specific Python Version
How to Convert Data from Txt Files to Excel Files Using Python
Replacing All Negative Values in Certain Columns by Another Value in Pandas