Yevhenii Chykalov
Yevhenii Chykalov

Reputation: 432

How to properly parse JSON file with duplicate keys?

I have a JSON string like:

{
   "result":
            {
              "event": {"date": "12/12/13", "desc": "test1"},
              "event": {"date": "12/12/14", "desc": "test2"},
              "event": {"date": "12/12/15", "desc": "test3"}
            },
  "result":
            {
              "event": {"date": "12/12/13", "desc": "test5"},
              "event": {"date": "12/12/14", "desc": "test6"},
              "event": {"date": "12/12/15", "desc": "test7"}
            }
}

I want to get all dates and descriptions of each event in all results, how to do it?

Upvotes: 0

Views: 318

Answers (1)

buran
buran

Reputation: 14263

You can use ijson package:

import ijson
with open('data.json') as f:
    events = list(ijson.items(f, 'result.event'))
print(events)

output:

[{'date': '12/12/13', 'desc': 'test1'}, {'date': '12/12/14', 'desc': 'test2'}, {'date': '12/12/15', 'desc': 'test3'}, {'date': '12/12/13', 'desc': 'test5'}, {'date': '12/12/14', 'desc': 'test6'}, {'date': '12/12/15', 'desc': 'test7'}]

Still, I think this duplicate keys should be avoided in JSON file.

Upvotes: 1

Related Questions