如何使用python解析json项?

时间:2016-01-26 19:38:08

标签: python json parsing

我正在尝试解析以下json数据,但我一直收到错误:

Error Type: <type 'exceptions.KeyError'>
Error Contents: ('channel',)
Traceback (most recent call last):
data=channels['channel']
KeyError: ('channel',)
-->End of Python script error report<--

任何人都可以告诉我如何解决上面的错误,并提前从json.Thanks解析所需的数据。

蟒:

url2 ='http://www.awebsite.com/json.php';
response = make_request(url2)
channels=json.loads(response)
data=channels['channel']

for item in data:
    name=item['title']
    thumb=item['logo']

    url=item['url1']
    add_link(name,url,4,thumb, thumb)

json:

  {
        "channels": [{
            "channel": {
                "id": "1",
                "title": "test1",
                "logo": "https:\/\/somewebsite.com\/1.jpg",
                "url1": "http:\/\/somewebsite2.com:80\/live\/hls\/1.m3u8",

            }
        }, {
            "channel": {
                "id": "2",
                "title": "test2",
                "logo": "https:\/\/somewebsite.com\/2.jpg",
                "url1": "http:\/\/somewebsite2.com:80\/live\/hls\/2.m3u8",
               }
        }]
    }

2 个答案:

答案 0 :(得分:1)

您忘记了字SharedPreferences sharedPref = this.getSharedPreferences("PREF_PERSONAL_DATA", Context.MODE_PRIVATE); String Weight = sharedPref.getString("we", null); int W = sharedPref.getInt("weight", 0); TextView ShowWeight = (TextView) findViewById(R.id.attempt); ShowWeight.setText(Weight); TextView ShowW = (TextView) findViewById(R.id.attemptW); ShowW.setText(W); 中的字母s。它必须是channels&lt; - 请参阅最后一句

您有数据

data=channels['channels']

不是

channels['channels'][0]['channel']['id']
channels['channels'][0]['channel']['title']

channels['channels'][1]['channel']['id']
channels['channels'][1]['channel']['title']

使用channels['channel'][0]['id'] channels['channel'][0]['title'] channels['channel'][1]['id'] channels['channel'][1]['title'] 查看。

编辑:工作示例

print(channels)

答案 1 :(得分:0)

channels=json.loads(response)创建一个名为channels的Python字典。此词典的顶级(基于您包含的json)是channels['channels']。当您尝试channels['channel']时出现关键错误,因为该字典的第一级不存在该键。

要访问channel实体,请尝试:channels['channels'][1]['channel']

你需要&#34; [1]&#34;因为channels['channels']channel个实体的列表。

您可以使用以下知识轻松构建数据:

data = [channel['channel'] for channel in channels['channels']]