Alexander Espiritu
Alexander Espiritu

Reputation: 69

Get property in nested JSON Python

I am trying to get the values of the properties in JSON but I'm having a hard time fetching the ones inside an object array.

I have a function that gets a test JSON which has these lines of code:

def get_test_body() -> str:
    directory = str(pathlib.Path(__file__).parent.parent.as_posix())
    f = open(directory + '/tests/json/test.json', "r")
    body = json.loads(f.read())
    f.close()  
    return body

This is the first half of the JSON file (modified the names):

"id": "112358",
"name": "test",
"source_type": "SqlServer",
"connection_string_name": "123134-SQLTest-ConnectionString",
"omg_test": "12312435-123123-41232b5-asd123-1232145",
"triggers": [
    {
        "frequency": "Day",
        "interval": 1,
        "start_time": "2019-06-17T21:37:00",
        "end_time": "2019-06-18T21:37:00",
        "schedule": [
            {
                "hours": [
                    2
                ],
                "minutes": [
                    0
                ],
                "week_days": [],
                "month_days": [],
                "monthly_occurrences": []
            }
        ]
    }
]

The triggers has more objects within it I couldn't figure out the syntax for it.

I am then able to fetch the some of the data using: name = body['name']

But I couldn't fetch anything under the triggers Array. I tried using body['triggers']['frequency'] and even ['triggers'][0] (lol) but I couldn't get it to work. I'm fairly new to Python any help would be appreciated!

Upvotes: 0

Views: 184

Answers (1)

Alexander Riedel
Alexander Riedel

Reputation: 1359

I getting the right output, even with bwhat you did?

import json
string = """
{
"id": "112358",
"name": "test",
"source_type": "SqlServer",
"connection_string_name": "123134-SQLTest-ConnectionString",
"omg_test": "12312435-123123-41232b5-asd123-1232145",
"triggers": [
    {
        "frequency": "Day",
        "interval": 1,
        "start_time": "2019-06-17T21:37:00",
        "end_time": "2019-06-18T21:37:00",
        "schedule": [
            {
                "hours": [
                    2
                ],
                "minutes": [
                    0
                ],
                "week_days": [],
                "month_days": [],
                "monthly_occurrences": []
            }
        ]
    }
]
}
"""
str_dict = json.loads(string)

print(str_dict["triggers"][0]["frequency"])

Giving me Day

Upvotes: 1

Related Questions