Home > other >  Django loop through json object
Django loop through json object

Time:06-14

How to loop through a JSON object in Django template?
JSON:

"data": {
 "node-A": {
    "test1A": "val1A",
    "test2A": "val2A",
    "progress": {
        "conf": "conf123A"
        "loc": "loc123A"
        },
    "test3A": "val3A"
    },
 "node-B": {
    "test1B": "val1B",
    "test2B": "val2B",
    "progress": {
        "conf": "conf123B"
        "loc": "loc123B"
        },
    "test3B": "val3B"
    }
}

I am having trouble accessing the nested values "conf" and "lock" inside "progress". How can I access them in Django template if the data is passed as context i.e. return (request, 'monitor.html', {"data_context": json_data['data']})?

CodePudding user response:

they way you have it set up, your data is in a dictionary called 'data_context'. To access what you need in the template it would be {{data_context.test1A}}.

to not have to use 'data_context.' try this instead,

return (request, 'monitor.html', json_data['data'].to_dict())

CodePudding user response:

Dictionary lookup, attribute lookup and list-index lookups are implemented with a dot notation:

  {{ my_dict.key.key_nested }}

CodePudding user response:

As the JSON format behaves like a dictionary in Python, the data stored with the specified keys conf and loc should be accessible with the python notation for dictionaries. Since the provided JSON can be seen as a nested dictionary, you need to "concat" the keys respectively to get your desired data.

Your return statement returns a dictionary which I will call ret so the structure should be:

{"data_context": {

    "node-A": {
        "test1": "val1A",
        "test2": "val2A",
        "progress": {
            "conf": "conf123A",
            "loc": "loc123A"
            },
        "test3": "val3A"
        },
     "node-B": {
        "test1B": "val1B",
        "test2B": "val2B",
        "progress": {
            "conf": "conf123B",
            "loc": "loc123B"
            },
        "test3": "val3B"
        }
    }
}

Therefor to access conf and loc:

ret["data_context"]["node-A"]["progress"]["conf"]

will get you the value stored at conf in node-A

  • Related