Python & Multilevel JSON File read and add - python

I am attempting to read the following JSON file and update it, specifically:
I can get the latest data analysis (var: lastAnalysisCompleted) was completed using get_json()
I get the following error code "list indices must be integers or slices, not str" when attempting to set baselineDictionaryFilename variable
I want to create a new grouping under the 'analysis' using the write_json() module. But running into errors.
How can I proceed?
New grouping:
"01-02-2020":{
"dictionaryFileName": "Dictionary_01-02-2020.json",
"analysisFileName": "Analysis_Output_01-02-2020.xlsx",
"netNewLabelledEntries": "10",
"range90": "1",
"range80": "3",
"range75":"1",
"rangeLessThan75":"5"
}
def get_json():
with open(jFile, 'r') as myfile:
data=myfile.read()
# parse file
obj = json.loads(data)
#secret = parsed_input['secret']
lastAnalysisCompleted = obj['lastAnalysisCompleted']
baselineDictionaryFileName = obj['analysis'][lastAnalysisCompleted]['dictionaryFileName']
Here is the module I wrote to update JSON but it doesn't work
def write_json(filename=jFile):
with open(filename, 'w') as f:
json.dump(data, f, indent=3)
with open(jFile) as json_file:
data = json.load(json_file)
temp = data['analysis']
y = {
"01-02-2020":{
"dictionaryFileName": "Dictionary_01-02-2020.json",
"analysisFileName": "Analysis_Output_01-02-2020.xlsx",
"netNewLabelledEntries": "10",
"range90": "1",
"range80": "3",
"range75":"1",
"rangeLessThan75":"5"
}
}
temp.append(y)
write_json(data)
Here is my JSON file.
{
"lastAnalysisCompleted": "01-01-2020",
"analysis":[
{
"12-31-2019":{
"dictionaryFileName": "Dictionary_12-31-2019.json",
"analysisFileName": "Analysis_Output_12-31-2019.xlsx",
"netNewLabelledEntries": "10",
"range90": "1",
"range80": "3",
"range75":"1",
"rangeLessThan75":"5"
},
"01-01-2020":{
"dictionaryFileName": "Dictionary_01-01-2020.json",
"analysisFileName": "Analysis_Output_01-01-2020.xlsx",
"netNewLabelledEntries": "10",
"range90": "1",
"range80": "3",
"range75":"1",
"rangeLessThan75":"5"
}
}
]
}

The problem in your code for getting the file name it is array of dicts you need to use index to access specific dictionary.
def get_json():
with open('test.json', 'r') as myfile:
data=myfile.read()
# parse file
obj = json.loads(data)
#secret = parsed_input['secret']
lastAnalysisCompleted = obj['lastAnalysisCompleted']
baselineDictionaryFileName = ''.join([d[lastAnalysisCompleted]['dictionaryFileName'] for d in obj['analysis'] if lastAnalysisCompleted in d])
And for writing to json file you are passing data to write_json() function and in function you are not defined argument for data
def write_json(data, filename=jFile):
with open(filename, 'w') as f:
json.dump(data, f, indent=3)

Related

How do i append at a json file at the end of the list with python

So i want to put some json strings like this
[{"username": "username", "key": "key"}, {"username": "username", "key": "key"}, ...]
i tried json.dump and json.dumps but it doesn't worked for me, please help me
this is the code that i written for now:
import json
username = input('Username to put in the keys file: ')
key = input('Key to put in the keys file: ')
uak = {"username": username, "key": key}
with open('keys.json', 'r') as r:
data = json.load(r)
with open('keys.json', 'w') as w:
json.dump(data, w)
Your keys.json file's content initially must be equal to [] that matchs an empty json array to append your objects at runtime, then you have to add your {"username": username, "key": key} json object to your data list with the append method like below:
#keys.json is initialized with []
import json
username = input('Username to put in the keys file: ')
key = input('Key to put in the keys file: ')
uak = {"username": username, "key": key}
with open('keys.json', 'r') as r:
data = json.load(r)
with open('keys.json', 'w') as w:
data.append(uak)
json.dump(data, w)

Modify a sub value of json file using python

I'm trying to create multiple JSON files with different numbers at specific value, this is my code :
import json
json_dict = {
"assetName": "GhostCastle#",
"previewImageNft": {
"mime_Type": "png",
"description": "#",
"fileFromIPFS": "QmNuFreEoJy9CHhXchxaDAwuFXPHu84KYWY9U7S2banxFS/#.png",
"metadataPlaceholder": [
{
"": ""
}
]
}
}
n = 10
for i in range(1, n+1):
json_dict["assetName"] = f"GhostCastle{i}"
json_dict[#What to put here to choose "fileFromIPFS"] = f"QmNuFreEoJy9CHhXchxaDAwuFXPHu84KYWY9U7S2banxFS/{i}.png"
with open(f"{i}.json", 'w') as json_file:
#json.dump() method save dict json to file
json.dump(json_dict, json_file)
so What to put to choose "fileFromIPFS" in the second json_dict

find and replace specific json data in python?

I am trying to replace data1 with data5 in json body of Full Address, but my code is giving error with these (list indices must be integers or slices, not str).
Please see my code as well as json body below.
json
[
{
"fields": {
"Full Address": "data1",
"pl/p/0": "212152",
"ot": "fgde"
}
},
{
"fields": {
"Full Address": "data2",
"pl/p/0": "52562",
"ot": "frtfr"
}
}
]
code
import json
with open('jsonbody.json') as f:
data = json.load(f)
for item in data['fields']:
item['Full Address'] = item['Full Address'].replace('data1', 'data5')
with open('new_data.json', 'w') as f:
json.dump(data, f)
the data is list, and its element is a dict, which contains fields key
import json
with open('jsonbody.json') as f:
data = json.load(f)
for item in data:
item['fields']['Full Address'] = item['fields']['Full Address'].replace('data1', 'data5')
with open('new_data.json', 'w') as f:
json.dump(data, f)
Here I am answering my own question with adding german umlaut detail.
import json
jsonbody = 'jsonbody.encode()'
with open('jsonbody.json', 'r') as file:
json_data = json.load(file)
for item in json_data:
if item['fields']['Full Address'] in ["data1"]:
item['fields']['Full Address'] = "data5_Ä"
with open('new_data.json', 'w') as file:
json.dump(json_data, file, indent=2)
# if my detail contain german words then I will use this
json.dump(json_data, file, indent=2, ensure_ascii=False)

Trouble with this error while adding a dict to an existing key value

Code Including JSON File Code:
Python( Suppose To Append A New User and Balance):
import json
with open('users_balance.json', 'r') as file:
data = json.load(file)['user_list']
data['user_list']
data.append({"user": "sdfsd", "balance": 40323420})
with open('users_balance.json', 'w') as file:
json.dump(data, file, indent=2)
Json(Object The Code Is Appending To):
{
"user_list": [
{
"user": "<#!672986823185661955>",
"balance": 400
},
{
"user": "<#!737747404048171043>",
"balance": 500
}
],
}
Error(Traceback Error Given After Executing Code):
data = json.load(file)['user_list']
KeyError: 'user_list'
The solution is this:
import json
with open('users_balance.json', 'r') as file:
data = json.load(file)
data['user_list'].append({"user": "sdfsd", "balance": 40323420})
with open('users_balance.json', 'w') as file:
json.dump(data, file, indent=2)

Python - write/ADD a new record in file with Json format

I want to add a new record at the end of my file Json, For now it contains
{
"1":
{
"coef":987,
"Term":
{
"x1":6,"x2":0,"x3":8
}
}
}
im reading this file like this :
try:
json_data=open ("/home/sage/content.txt")
data=json.load (json_data)
except IOError:
print "Can't open your file"
how to add a new record at the end of file.
After reading the data , you can't add to the file, you need to create a new file (with the same name if you want):
data['added_data'] = 'some data added'
write_file = open("/home/sage/content.txt", "w")
write_file.write(json.dumps(data))
If you are using python 2.5 or newer you should use with statement dealing with files:
import json
with open('content.txt', 'r') as f:
data = json.load(f)
data["2"] = {
"coef":987,
"Term":
{
"x1":6,"x2":0,"x3":8
}
}
with open('content.txt', 'w') as f:
json.dump(data, f)

Categories