0

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?

martineau
  • 119,623
  • 25
  • 170
  • 301
Yevhenii Chykalov
  • 380
  • 1
  • 2
  • 13
  • 2
    _I have a JSON string_ - no, you don't have JSON, becaise it's not valid one. – buran Nov 04 '21 at 20:58
  • 1
    @buran Seems to be a bit of a grey area -- https://stackoverflow.com/questions/21832701/does-json-syntax-allow-duplicate-keys-in-an-object -- but you're right, most parsers won't allow it since the spec *recommends* against duplicate keys. – Brendan Abel Nov 04 '21 at 20:59
  • 3
    What I would do in this case is use a text editor (or simple script) to change the first and last `{ }` to `[ ]` and delete the lines that say `"result":`. Now you have a valid JSON list that you can import and process. – Tim Roberts Nov 04 '21 at 21:00
  • @BrendanAbel Yeah, I agree it's bit of gray area. But as mentioned in the same link, in the case where there are duplicate name Strings within an object, lexically preceding values for the same key shall be overwritten. i.e. last-seen-wins. There will be no error if they parse it with `json` module, but also will not get all the values. – buran Nov 04 '21 at 21:07

1 Answers1

1

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.

buran
  • 13,682
  • 10
  • 36
  • 61