0

I am working with an API (which I have no control over) that returns a response with hundreds of duplicate keys:

{
  "user": {
    //...
  },
  "user": {
    //...
  },
  //...
}

Using response.json() will only return one object, since it will overwrite any duplicate keys. Is there any way I can take the full response from response.text and turn it into something that I can parse to json?

Majs
  • 607
  • 2
  • 7
  • 20

2 Answers2

0

Based on the answer to Python json parser allow duplicate keys, this seems to work:

from json import JSONDecoder

def parse_object_pairs(pairs):
    return pairs

data = """
{
  "user": {
    "val":[1,2,3]
  },
  "user": {
    "val":[1,2,3]
  }
}
"""

decoder = JSONDecoder(object_pairs_hook=parse_object_pairs)
obj = decoder.decode(data)
print (obj)
# [('user', [('val', [1, 2, 3])]), ('user', [('val', [1, 2, 3])])]
phhu
  • 1,462
  • 13
  • 33
0

You can use the object_pairs_hook argument to json.loads().

text = """
{
    "user": "Adam",
    "user": "Bill"
}
"""

import json

def hook(key_value_pairs):
    users = []
    for key, value in key_value_pairs:
        if key == "user":
            users.append(value)
    return {
        "users": users
    }

data = json.loads(text, object_pairs_hook=hook)
print(data)
# {'users': ['Adam', 'Bill']}
phhu
  • 1,462
  • 13
  • 33
md2perpe
  • 3,372
  • 2
  • 18
  • 22