1
{
    "event": {
        "firstEventHeader": {
            "domain": "someDomain",
            "eventId": "event001",
            "priority": "Normal",
            "startTimer": timeInMicroSec
        },
        "secondEventHeader": {
            "additionalHeader": [
                {
                    "header": [
                        {
                            "Name": "Name1",
                            "Value": "value1"
                        },
                        {
                            "Name": "Name2",
                            "Value": "value2"
                        },
                        {
                            "Name": "Name3",
                            "Value": "value3"
                        },
                   ],
                    "name": "Field1"
                },

        "thirdEventHeader": {
            "additionalHeader": [
                {
                    "header": [
                        {
                            "Name": "Name4",
                            "Value": "value4"
                        },
                        {
                            "Name": "Name5",
                            "Value": "value5"
                        },
                        {
                            "Name": "Name6",
                            "Value": "value6"
                        },

                    ],
                    "name": "Field2"
                },

I have a file in above format which is getting generated dynamically using a Python script.

I want to access startTimer from firstEventHeader and then name and value from secondEventHeader & thirdEventHeader. Eg.

startTimer : 12345678
    Name1:value1
    Name2:value2
    Name3:value3
    Name4:value4 
    Name5:value5
    Name6:value6

Note: JSON format data is available inside a different file format other than .json. So loading the json will not work as file format is different.

newbie
  • 21
  • 3

2 Answers2

0

You can use the json built-in library. Assuming you can get the json data into some string, this should get you started:

import json

d = json.loads(string)
print(d['event']['firstEventHeader']['startTimer'])

You'll want to do some iteration to get all the Name:Value pairs.

Jeremy McGibbon
  • 3,527
  • 14
  • 22
0

If the file is in this format, load it using the json module into a dictionary. You can then traverse that dictionary.

import json
with open('filename') as f:
  data == json.load(f)

e = data['event']
print("Start timer:", e['firstEventHeader']['startTimer'])
def process_header(header_fields):
  for x in header_fields:
    print("Name:", x['Name'], ", Value:", x['Value'])

print("Second event header")
process_header(e['secondEventHeader']['additionalHeader']['header'])

print("Third event header")
process_header(e['thirdEventHeader']['additionalHeader']['header'])
orip
  • 73,323
  • 21
  • 116
  • 148