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?

4
  • 2
    I have a JSON string - no, you don't have JSON, becaise it's not valid one. Commented Nov 4, 2021 at 20:58
  • 1
    @buran Seems to be a bit of a grey area -- stackoverflow.com/questions/21832701/… -- but you're right, most parsers won't allow it since the spec recommends against duplicate keys. Commented Nov 4, 2021 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. Commented Nov 4, 2021 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. Commented Nov 4, 2021 at 21:07

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.