我试图存储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' –