2016-03-24 108 views
2

我正在通過API從GET請求中提取JSON數據,並且我無法將響應連接在一起。我對字典和索引(以及python)很陌生。將兩個API調用與JSON合併

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 

謝謝你,讓我知道如果您需要了解更多信息!

+0

另外:'requests'有一個解析json的快捷方式:'obj1 = response.json()'。 –

+0

您是否需要獲得有效的API答案,或者只需要獲取所有項目? –

+0

請生成一個沒有無關代碼的[mcve]。擺脫對「請求」的調用。擺脫對'json'的調用。只需創建兩個'dict'對象,並展示你如何合併它們,結果如何,以及你希望得到的結果是什麼。這應該是一個簡短的(5-10行),完整的程序,我們可以運行並重現您的結果。 –

回答

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將包含來自每個響應的所有項目。

1

讓我們假設你的JSON響應如下所示:

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

對於OBJ 2:

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

你需要轉換的JSON響應快譯通,然後追加該字典對象的數組:

[{"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":{}}] 
+0

這就是數據看起來像 '{u'count':25373,u'items':[{u'closedBy':None,u'cc ':None,u'number':98976,u'owner':{u'firstName':u'joe',u'lastName':u'Shmoe',u'email':u'[email protected]。 'u'phone':沒有,u'type':u'user',u'id':74336},u'id':432345,u'createdAt':u'2016-03-24T17:16: 05Z',u'subject':u'Mail',u'folderId':1234323,u'spam':False,u'createdByType':u'customer',u'isDraft':False,u'source':{ u'via':u'customer',u'type':u'email'},u'draft':假的,u'preview':你的一些文字。 '''','''''''','''','''''''''''',''''...' –

+0

如果這就是現在的樣子,你的程序改變它後,你希望它看起來像什麼? –