在python中存储这个JSON的正确方法?

时间:2015-11-14 05:24:46

标签: python json

我正在尝试存储从网站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

3 个答案:

答案 0 :(得分: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.

答案 1 :(得分: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

无需转换为字符串和从字符串转换。

答案 2 :(得分:0)

试试这个:

public Game() {
    // Frame
    JFrame container = new JFrame("Space Invaders");

    // Resolution
    JPanel panel = (JPanel) container.getContentPane();
    panel.setPreferredSize(new Dimension(800,600));
    panel.setLayout(null);

    // Canvas Size
    panel.setBounds(0,0,800,600);
    panel.add(this);

    // Window Visible
    container.pack();
    container.setResizable(false);
    container.setVisible(true);

    container.addWindowListener(new WindowAdapter() {
        public void windowClosing(WindowEvent e) {
            System.exit(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

注意:您仍然必须进行错误处理。