我試圖存儲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
爲什麼你想*轉換單引號中'response_content' *?爲什麼不把它像'import json; json.dumps(response_content)'? –
你想通過將'response.json()'串化來改變引號,然後重新解析爲JSON來完成什麼? – jwodder
我試過'json_data = json.dumps(response_content);打印(鍵入(json_data))',它說這是''。我想做一些像'xkcd_num = json_data ['num']'但是這會返回一個錯誤,比如'TypeError:string indices must be integers' –