skip to Main Content

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


  1. jsondata["Job"]["LoggingData"]["Logs"] in your example is a list of dictionaries so the first condition is False that’s why else comes into play and adds your data to the Logs list.

    If you want it to make it work in your example, you should check it that way

    if "LogDetails" in jsondata["Job"]["LoggingData"]["Logs"][0]:
        ...
    

    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.

    Login or Signup to reply.
  2.     if "LogDetails" in jsondata["Job"]["LoggingData"]["Logs"]:
            jsondata["Job"]["LoggingData"]["Logs"]["LogDetails"].append(new_data)
    

    This would have worked as intended if your initial jsonfile looked like

    jsonfile = {
        "Job": {
            "id": "",
            "LoggingData": {
                "Logs":{"LogDetails": [{}]} ## NOT [{"LogDetails": [{}]}]
            }
        }
    }
    

    However, 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 in Logs, you should change that if block to

        if "LogDetails" in jsondata["Job"]["LoggingData"]["Logs"][0]:
            print("Joy - Found LogDetails") 
            jsondata["Job"]["LoggingData"]["Logs"][0]["LogDetails"].append(new_data)
    

    Use ...["Logs"][-1]... (instead of ...["Logs"][0]...) if you want to add new_data to the last dictionary in Logs. [Ofc, it won’t make a difference if Logs has only one item.]

    Btw, you could also use isinstance and .setdefault [or even just try...except] to check for and ensure your data structure.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search