How to Update JSON File with Python

Update json data from a python file


import json

#here you get data information as `intents` as you have done in your code

#now open your sample.json file and load it

with open('sample.json') as json_file:
data = json.load(json_file)

#now you have data["intents"] from json file and new intents from your db
# the two intents are list of dict . So you can add both obtaining a new list with the elements of the first `intents` and the elements of the second `intents`.

intents = {"intents" : data["intents"]+intents["intents"]}

#so now , you can save `intents` as a new json , like before.

with open("sample.json", "w") as outfile:
json.dump(intents, outfile)

All in one...

import firebase_admin
from firebase_admin import credentials
from firebase_admin import firestore
import json
import os

cred = credentials.Certificate("firebasekey.json")
firebase_admin.initialize_app(cred)

db = firestore.client()

#read data
#Getting a Document with a known ID

intents = {"intents": []}
results = db.collection('users').document('HtregtuuDDVWglz9DjobFGH9jMo1').collection('chats').get()

#---------------------------------------
# don' t need this
# with open('intents.json') as json_file:
# data = json.load(json_file)
#----------------------------------------

for index, result in enumerate(results):
data = result.to_dict()
intents["intents"].append({
"tag": f"firebase data{index}",
"patterns": [data["message"]],
"responses": [data["message"]]
})

print("Log intents: ",intents)

#-------with the new part

#First be sure the file exists and it's not empty. At least it must be structured like this: {"intents":[]}

with open('intents.json') as json_file:
data = json.load(json_file)

print("Log data: ",data)

intents = {"intents": data["intents"]+intents["intents"]}

print("Log new intents: ",intents)

with open("intents.json", "w") as outfile:
json.dump(intents, outfile)

Seems to be ok . But i can't test each parts of the code.

Test it and let me know.

Update JSON file in Python

You would want to do something along the lines of:

def append_statistics(filepath, num_of_posts, followers, following):

with open(filepath, 'r') as fp:
information = json.load(fp)

information["statistics"].append({
"date": datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
"num_of_posts": num_of_posts,
"followers": followers,
"following": following
})

with open(filepath, 'w') as fp:
json.dump(information, fp, indent=2)

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'}}}

Update a JSON file with Python and keep the original format

Try json.dumps(json_obj, indent=4)

Example:

import json

status_wifi = "ok"

with open("config_wifi.json", "r") as jsonFile:
data = json.load(jsonFile)
data['wifi_session']['status'] = status_wifi

with open("config_wifi.json", "w") as jsonFile:
json.dump(json.dumps(data, indent=4), jsonFile)

The indent is the number of spaces for a tab.
If you set this parameter, the JSON will be formatted.

You can read more about it here.

How to update key's value in json file by Python

Here is the issue:

data["num"]+=([num_list])

You are assuming that num_list is not an array and you are currently wrapping it inside another one. So you are adding not a list of values but another array to your currently stored inside the json data.

To solve this just change your code to:

data["num"]+=num_list

Besides that, you are writing in append mode and you are updating the json data on memory before writing to disk. Change the mode to write like this:

# change
f = open("data.json", "a")
# to
f = open("data.json", "w")

About the output you shared there is a weird format at the start. Is that right?

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)

How to update json object in a loop?

You need to put all the state information into a list. Then you can simply append each dictionary to that list. There's nothing to update, since each dictionary is a separate element of the list

import json

info = {
"name": "master",
"states": []
}

states = ["MN", "AZ", "IL"]
cities = ["One", "Two", "Three"]
votes = ["No", "Yes", "Maybe"]

for state in states:
for city in cities:
for vote in votes:
info['states'].append({
"state": state,
"cities": {
"name": city,
"votes": { "decision": vote }
}
});

print(json.dumps(info, indent=4))

DEMO

I wonder, though, if this is really the result you want. You have a key called cities; the name suggests that it should contain more than one city, but it only contains one -- you have each city in a separate state dictionary. The same thing goes for votes -- it's just one vote, not all of the votes for that city.

Python read JSON file and modify

Set item using data['id'] = ....

import json

with open('data.json', 'r+') as f:
data = json.load(f)
data['id'] = 134 # <--- add `id` value.
f.seek(0) # <--- should reset file position to the beginning.
json.dump(data, f, indent=4)
f.truncate() # remove remaining part

How to rewrite JSON file in gitlab from python

Use the files api file object. Reference

f = project.files.get(file_path='README.rst', ref='main')
decoded_content = f.decode()
new_content = modify_content(decoded_content) # you implement this

# update the contents and commit the changes
f.content = new_content
f.save(branch='main', commit_message='Update file')

You can use json.dumps to get a string for the new content.

f.content = json.dumps(data)
f.save(...)


Related Topics



Leave a reply



Submit