获取JSON对象python的子代

时间:2016-11-28 14:45:42

标签: json python-2.7

我试图在python 2.7中解析一些json数据,但不知道如何获取子元素。

对象结构是这样的:

{
    "35": {
        "num": 1,
        "name": "Discovery",
        "stream_type": "live",
        "stream_id": "35"
    },
    "13085": {
        "num": 2,
        "name": "Discovery HD",
        "stream_type": "live",
        "stream_id": "13085"
    },
    "36": {
        "num": 3,
        "name": "Discovery Investigation",
        "stream_type": "live",
        "stream_id": "36"
    },
    "151": {
        "num": 4,
        "name": "Discovery Turbo",
        "stream_type": "live",
        "stream_id": "151"
    }

}

我使用urllib2从url加载它,然后使用for循环迭代它:

> import urllib2,json
> 
> data = urllib2.urlopen("http://someurl.eu/json.php") data =
> data.read().decode("utf-8") channels = json.loads(data)
> 
> for channel in channels:
>     print channel   #prints the id's

但我如何进一步发展?

如果我尝试:

for channel in channels:
    print channel   #prints the id's
    print channel['name']  #trying to get name

然后我得到:

  

TypeError:字符串索引必须是整数

我认为它需要像print channel [0]之类的东西,但这只是打印我的第一个id。

我也用其他方式玩过它,但我从来没有成功,任何人都可以解释一下,应该怎么做?

1 个答案:

答案 0 :(得分:5)

对于频道中的频道,通过字典键进行迭代。

您可以遍历值而不是键:

for channel in channels.values():
    print channel   # prints the entire channel
    print channel['name']  # prints name

或迭代密钥但访问字典中的数据:

for channel in channels:
    print channel   # prints the id
    print channels[channel]['name']  # prints name