2

If I have JSON with duplicate keys and different values in each of the duplicate keys, how can I extract both in python?

ex:

{ 
   'posting': {
                'content': 'stuff',
                'timestamp': '123456789'
              }
   'posting': {
                'content': 'weird stuff',
                'timestamp': '93828492'
              }
}

If I wanted to grab both timestamps, how would I do so?

I tried a a = json.loads(json_str) and then a['posting']['timestamp'] but that only returns one of the values.

Liondancer
  • 14,518
  • 43
  • 138
  • 238
  • I suppose you could parse it by hand but this seems like a bad idea. Best option is to change the JSON as it is invalid. You should use a list instead. – Cfreak Mar 23 '15 at 04:18
  • You cannot have duplicate key in a dictionary. – Balkishan Mer Mar 23 '15 at 04:20
  • 1
    Duplicate keys in JSON aren't covered by the spec and can lead to undefined behavior (see [this question](http://stackoverflow.com/questions/21832701/does-json-syntax-allow-duplicate-keys-in-an-object)). If you read the JSON into a Python dict, the information will be lost, since Python dict keys must be unique. Your best bet is to change the JSON; duplicate keys are a bad idea. – BrenBarn Mar 23 '15 at 04:22
  • Why do you have duplicate keys? – user2357112 Mar 23 '15 at 05:43
  • 1
    @user2357112 I didnt plan this, someone else did and I have to deal with it =[ – Liondancer Mar 23 '15 at 05:49

2 Answers2

3

You can't have duplicate keys. You can change the object to array instead.

[
    {
        'content': 'stuff',
        'timestamp': '123456789'
    },
    {
        'content': 'weird stuff',
        'timestamp': '93828492'
    }
]
mailtosumitrai
  • 691
  • 1
  • 7
  • 16
2

Duplicate keys actually overwrite the previous entry. Instead you maintain an array for that key. Example json is as below

{

'posting' : [
              {
                'content': 'stuff',
                'timestamp': '123456789'
              },
              {
                'content': 'weird stuff',
                'timestamp': '93828492'
              }
            ]

}

you can now access different elements in posting key like this

json.posting[0] , json.posting[1]