1

my json looks like below, i want to loop through and parse this using python. pls need some idea since i am new to python. please note that, my json is not having root element as well as split(,)

{
    "httpRequest": {
        "status": 200
    }, 
    "protoPayload": {
        "resource": "/food/android?event_name=afo_product1_clicked", 
        "startTime": "2021-04-12T07:26:02.019507Z"
    }, 
    "receiveTimestamp": "2021-04-12T07:26:02.176159139Z"
}
{ 
    "httpRequest": {
        "status": 200
    }, 
    "protoPayload": {
        "resource": "/food/android?event_name=afo_addtocart_clicked",
        "startTime": "2021-04-12T07:26:02.019507Z"
    }, 
    "receiveTimestamp":"2021-04-12T07:26:02.176159139Z"
}
matiaslauriti
  • 7,065
  • 4
  • 31
  • 43
thiru
  • 47
  • 1
  • 6

1 Answers1

0

correctly formatted the json string by ref : How to add commas in between JSON objects present in a .txt file and then convert it into JSON array in Python

and the correctly formatted json is:

{
"httpRequest":{"status":200}, 
"protoPayload":{"resource":"/food/android?event_name=afo_product1_clicked", 
"startTime":"2021-04-12T07:26:02.019507Z"}, 
"receiveTimestamp":"2021-04-12T07:26:02.176159139Z"
},

{ 
"httpRequest":{"status":200}, 
"protoPayload":{"resource":"/food/android?event_name=afo_addtocart_clicked", 
"startTime":"2021-04-12T07:26:02.019507Z"}, 
"receiveTimestamp":"2021-04-12T07:26:02.176159139Z"
}

code:

import json

parser = json.JSONDecoder()
parsed = []  # a list to hold individually parsed JSON structures
with open('test.json') as f:
   data = f.read()
   head = 0  # hold the current position as we parse
   while True:
      head = (data.find('{', head) + 1 or data.find('[', head) + 1) - 1
      try:
        struct, head = parser.raw_decode(data, head)
        parsed.append(struct)
      except (ValueError, json.JSONDecodeError):  # no more valid JSON structures
    break

  print(json.dumps(parsed, indent=2))  # make sure it all went wellclear
thiru
  • 47
  • 1
  • 6