I’m trying to add a element to a json file, but i can add it to the level 4 of the file (LogDetails), however, it works for level 3 (Logs).
I’m all new to Python and i can seem to figure this out, can someone help? 🙂
import json
#Normaly loaded from a json file, but inserted here to make the exampel more simple - i hope :)
jsonfile = {
"Job": {
"id": "",
"LoggingData": {
"Logs":[{
"LogDetails": [{
}]
}]
}
}
}
def AddToJson(new_data,jsondata=""):
print("jsondata type:", type(jsondata))
if "LogDetails" in jsondata["Job"]["LoggingData"]["Logs"]:
print("Joy - Found LogDetails")
jsondata["Job"]["LoggingData"]["Logs"]["LogDetails"].append(new_data)
else:
for sub in jsondata["Job"]["LoggingData"]["Logs"]:
print("Value of sub:"+str(sub))
jsondata["Job"]["LoggingData"]["Logs"].append(new_data)
return(jsondata)
DataToAddToExistingJson = {"Step id": 1, "Step name": "Test"}
NewJsonfile =AddToJson(new_data=DataToAddToExistingJson,jsondata=jsonfile)
print ("NewJsonfile type:",type(NewJsonfile))
print ("NewJsonfile value:",NewJsonfile)
Output:
jsondata type: <class 'dict'>
Value of sub:{'LogDetails': [{}]}
NewJsonfile type: <class 'dict'>
NewJsonfile value: {'Job': {'id': '', 'LoggingData': {'Logs': [{'LogDetails': [{}]}, {'Step id': 1, 'Step name': 'Test'}]}}}
PS C:>
I would have expected it to find the lowest level of the dict named LogDetails, but it seems to ignore it.
Wanted output for first run:
{
"Job": {
"id": "",
"LoggingData": {
"Logs": [{
"LogDetails": [{
"Step id": 1,
"Step name": "Test"
}]
}]
}
}
}
and the afterwards something like this:
{
"Job": {
"id": "",
"LoggingData": {
"Logs": [{
"LogDetails": [{
"Step id": 1,
"Step name": "Test"
}, {
"Step id": 2,
"Step name": "Test"
}]
}]
}
}
}
2
Answers
jsondata["Job"]["LoggingData"]["Logs"]
in your example is a list of dictionaries so the first condition isFalse
that’s why else comes into play and adds your data to theLogs
list.If you want it to make it work in your example, you should check it that way
then the first condition would be
True
.But it might break if
Logs
would be an empty list (since this is not clear from your question), so you have to check if it’s there.This would have worked as intended if your initial
jsonfile
looked likeHowever, what you have is
..."Logs":[{"LogDetails": [{}]}]...
; so,jsondata["Job"]["LoggingData"]["Logs"]
is a list (from which items can be accessed with indices, not keys), so you can’t check in it for"LogDetails"
which is a key in the dictionary that is the first item in said list (i.e.,jsondata["Job"]["LoggingData"]["Logs"][0]
).To add
new_data
to the first dictionary inLogs
, you should change thatif
block toUse
...["Logs"][-1]...
(instead of...["Logs"][0]...
) if you want to addnew_data
to the last dictionary inLogs
. [Ofc, it won’t make a difference ifLogs
has only one item.]Btw, you could also use
isinstance
and.setdefault
[or even justtry...except
] to check for and ensure your data structure.