将两个API调用与JSON合并

时间:2016-03-24 16:39:43

标签: python json

我通过API从GET请求中提取JSON数据,但我无法将响应连接在一起。我是字典和索引的新手(以及那种方式的python)。

API数据是相同的,它只是一个不同的页码。能够通过eclipse调试器进行验证。我能够确认每个API调用都能够提取它所需的数据。

#pulls from the API
response = requests.get(url, headers=headers)

obj_json = response.content
objLoader = json.loads(obj_json)
obj1 = objLoader

#url changes to page 2
response = requests.get(url, headers=headers)

obj_json = response.content
obj1 = json.loads(obj_json)

newObj = dict(obj1.items() + obj2.items())
#I have also tried the following:
#dict(obj1.items() | obj2.items())

最后我想把obj2附加到obj1。

#Let's say obj1 has:
indexes[0][1]
#and obj2 has 
indexes [0][1]
#I'd like obj1 to have 
indexes[0][1][2][3]

obj1& 2项数据的结构如下:

obj1/2: dict u'count': 25370, u'items': [{..........}]

__len__: int: 508
count: int 25370
items: <type 'list'>: [{...}]
page: int
pages: int

谢谢,如果您需要更多信息,请告诉我们!

2 个答案:

答案 0 :(得分:2)

让我们假设您的JSON响应如下所示:

{"ID":1,"name":"Donald","first-name":"Trump","age":25,"hobbies":["tweet","hunting",{"sports":["volley-ball","golf"]}],"address":{}}

对于Obj2:

{"ID":2,"name":"Barack","first-name":"Obama","age":25,"hobbies":["reading","cinema",{"sports":["volley-ball","badminton"]}],"address":{}}

您需要将JSON响应转换为dict,然后将此字典附加到对象数组:

 [{"ID":1,"name":"Donald","first-name":"Trump","age":25,"hobbies":["tweet","hunting",{"sports":["volley-ball","golf"]}],"address":{}},{"ID":2,"name":"Barack","first-name":"Obama","age":25,"hobbies":["reading","cinema",{"sports":["volley-ball","badminton"]}],"address":{}}]

答案 1 :(得分:1)

你可以这样做:

url_header_list = [
    (url1, headers1),
    (url2, headers2),
    (url3, headers3),
    ...
]

items = []
# You can change your headers and url in any way you want, not just like that
for url, headers in url_header_list:
    # And this you need to do for each pair of url and headers
    response = requests.get(url, headers=headers).json()
    items.extend(response['items'])

items将包含每个回复中的所有项目。