[英]Correct way to store this JSON in python?
我正在嘗試存儲從網站https://www.xkcd.com/info.0.json返回的 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.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。 這可能看起來像它的工作str()
,因為 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.
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
無需在字符串之間進行轉換。
嘗試這個:
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()
注意:您仍然必須進行錯誤處理。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.