2015-11-14 195 views
-2

我試圖存儲JSON對象從網站https://www.xkcd.com/info.0.json在python中存儲這個JSON的正確方法是什麼?

我已經試過

url = 'https://www.xkcd.com/info.0.json' 
response = requests.get(url) 
if response.status_code == 200: 
    response_content = str(response.json()) 
    print(response_content) 
    new_response = response_content.replace("'", '"') 
    json_data = json.loads(new_response) 
    print(new_response) 
    print(json_data) 

print(response_content)回報

{ 
    'link': '', 
    'month': '11', 
    'num': 1603, 
    'title': 'Flashlights', 
    'safe_title': 'Flashlights', 
    'year': '2015', 
    'day': '13', 
    'img': 'http: //imgs.xkcd.com/comics/flashlights.png', 
    'transcript': '', 
    'news': '', 
    'alt': "Due to a typo, I initially found a forum for serious Fleshlight enthusiasts, and it turns out their highest-end models are ALSO capable of setting trees on fire. They're impossible to use without severe burns, but some of them swear it's worth it." 
} 

要將單引號轉換成response_content返回,我嘗試過

new_response = response_content.replace("'", '"') 

但問題與線出現在那裏alt

..... 
    "news": "", 
    "alt": "Due to a typo, ...... of setting trees on fire. They"reimpossibletousewithoutsevereburns, 
butsomeofthemswearit"s worth it.", 
} 

如果裏面有任何值的單引號,這種方法失敗。

錯誤日誌:

File "./main.py", line 55, in download_latest 
    json_data = json.loads(new_response) 
    File "/usr/lib/python3.4/json/__init__.py", line 318, in loads 
    return _default_decoder.decode(s) 
    File "/usr/lib/python3.4/json/decoder.py", line 343, in decode 
    obj, end = self.raw_decode(s, idx=_w(s, 0).end()) 
    File "/usr/lib/python3.4/json/decoder.py", line 359, in raw_decode 
    obj, end = self.scan_once(s, idx) 
ValueError: Expecting ',' delimiter: line 1 column 342 (char 341) 

加載的JSON在腳本中任何其他的方法呢?

編輯

我要像做

json_data = json.dumps(response_content) 
    print(type(json_data))  ## returns <class 'str'> 
    print(json_data['num'])  

但這返回TypeError

File "./main.py", line 53, in download_latest 
    print(json_data['num']) 
TypeError: string indices must be integers 
+6

爲什麼你想*轉換單引號中'response_content' *?爲什麼不把它像'import json; json.dumps(response_content)'? –

+1

你想通過將'response.json()'串化來改變引號,然後重新解析爲JSON來完成什麼? – jwodder

+0

我試過'json_data = json.dumps(response_content);打印(鍵入(json_data))',它說這是''。我想做一些像'xkcd_num = json_data ['num']'但是這會返回一個錯誤,比如'TypeError:string indices must be integers' –

回答

4

response.json()方法返回Python數據結構。你在這裏做的很多,你只需要:

url = 'https://www.xkcd.com/info.0.json' 
response = requests.get(url) 
if response.status_code == 200: 
    json_data = response.json() 

就是這樣。

您正在將Python數據結構轉換爲字符串,然後嘗試再次將該字符串解釋爲JSON。這可能看起來像它的工作,因爲Python容器的str()轉換使用Python語法來產生結果。但是Python不是JSON,不管怎樣,你試圖把它變成JSON也是不太好的。並且根本不需要

您可以直接使用json_data,它是一個Python字典:

>>> import requests 
>>> url = 'https://www.xkcd.com/info.0.json' 
>>> response = requests.get(url) 
>>> response.status_code 
200 
>>> json_data = response.json() 
>>> type(json_data) 
<type 'dict'> 
>>> json_data 
{u'img': u'http://imgs.xkcd.com/comics/flashlights.png', u'title': u'Flashlights', u'month': u'11', u'num': 1603, u'link': u'', u'year': u'2015', u'news': u'', u'safe_title': u'Flashlights', u'transcript': u'', u'alt': u"Due to a typo, I initially found a forum for serious Fleshlight enthusiasts, and it turns out their highest-end models are ALSO capable of setting trees on fire. They're impossible to use without severe burns, but some of them swear it's worth it.", u'day': u'13'} 
>>> print json_data['title'] 
Flashlights 
>>> print json_data['alt'] 
Due to a typo, I initially found a forum for serious Fleshlight enthusiasts, and it turns out their highest-end models are ALSO capable of setting trees on fire. They're impossible to use without severe burns, but some of them swear it's worth it. 
+0

我不知道'response.json()'返回了一個'dict'對象。很好的解釋@Martijin :) –

+2

@prodicus:它返回解碼的JSON結構。大多數API使用JSON對象,所以結果通常是字典,但是JSON數組也可以(給你一個列表),或任何JSON基元(字符串,整數,浮點數,布爾值,空值)。 –

+1

@prodicus:在這種情況下,它是一個字典,因爲這是JSON響應中的內容。 –

0

試試這個:

import json, requests 

r = requests.get('https://www.xkcd.com/info.0.json') 
responseJSON = None 
if r.status_code == 200: 
    responseJSON = json.loads(r.content) 

print responseJSON # you can access values like responseJSON['img'] 

因爲在這裏,你肯定有JSON響應的,你不妨做

responseJSON = r.json() 

注意:您仍必須做錯誤處理。

+0

'>>> responseJSON == r.json()': 'True' –

+0

@KevinGuan更好!我會補充說,替代方法 – activatedgeek

2

response.json()已經返回一個Python字典:

import requests 
import json 
url = 'https://www.xkcd.com/info.0.json' 
response = requests.get(url) 
if response.status_code == 200: 
    response_content = response.json() 
    print response_content 

無需轉換和從字符串。

+1

看,'請求'的魔力! –

相關問題