2016-11-29 22 views
2

我很難嘗試從import.io加載API響應到文件或列表中。使用Python從import.io加載JSON行問題

我使用的是enpoint https://data.import.io/extractor/{0}/json/latest?_apikey={1}

以前我的所有腳本都設置爲使用JSON正常,一切都運作良好,但現在嘿已經決定使用JSON行,但不知何故,它似​​乎格式不正確。

我試着去適應我的腳本的方法是閱讀下列方式API響應:

url_call = 'https://data.import.io/extractor/{0}/json/latest?_apikey={1}'.format(extractors_row_dict['id'], auth_key) 
r = requests.get(url_call) 

with open(temporary_json_file_path, 'w') as outfile: 
    json.dump(r.content, outfile) 

data = [] 
with open(temporary_json_file_path) as f: 
    for line in f: 
     data.append(json.loads(line)) 

這樣做的問題是,當我檢查數據[0],所有的JSON文件內容被傾倒在它...

data[1] = IndexError: list index out of range 

這裏是data[0][:300]一個例子:

u'{"url":"https://www.example.com/de/shop?condition[0]=new&page=1&lc=DE&l=de","result":{"extractorData":{"url":"https://www.example.com/de/shop?condition[0]=new&page=1&lc=DE&l=de","resourceId":"23455234","data":[{"group":[{"Brand":[{"text":"Brand","href":"https://www.example.com' 

有沒有人有與此API的響應經驗? 所有其他jsonline讀取我從其他來源做的工作很好,除了這一個。基於評論

編輯:

print repr(open(temporary_json_file_path).read(300)) 

給出了這樣的:

'"{\\"url\\":\\"https://www.example.com/de/shop?condition[0]=new&page=1&lc=DE&l=de\\",\\"result\\":{\\"extractorData\\":{\\"url\\":\\"https://www.example.com/de/shop?condition[0]=new&page=1&lc=DE&l=de\\",\\"resourceId\\":\\"df8de15cede2e96fce5fe7e77180e848\\",\\"data\\":[{\\"group\\":[{\\"Brand\\":[{\\"text\\":\\"Bra' 
+0

等一下,什麼?您的輸出看起來像您(或他們)添加了API內容的'repr()',因此JSON行編碼爲Python文字。 'print repr(open(temporary_json_file_path).read(300))'看起來像什麼? –

+0

在問題中增加了編輯 – johan855

+0

是的,數據是* double-encoded *。這看起來像import.io端的錯誤。他們的拼搶工作如何?你寫了一些代碼?如果是這樣,請不要將編碼轉換爲JSON,因爲它看起來像輸出自動以JSON編碼。 –

回答

5

你必須在你的代碼,你是雙編碼的錯誤:

with open(temporary_json_file_path, 'w') as outfile: 
    json.dump(r.content, outfile) 

嘗試:

with open(temporary_json_file_path, 'w') as outfile: 
    outfile.write(r.content) 
+2

我不知道我是如何錯過的。我刪除了我的錯誤答案。 –

+0

讓我試試看 – johan855