为什么我没有列表

时间:2015-03-30 07:55:17

标签: python json list python-2.7

我有这个json文件

{
"children": [{
        "objName": "Sprite1",
        "scripts": [[69,
                57,
                [["whenGreenFlag"],
                    ["broadcast:", "Pin D On"],
                    ["wait:elapsed:from:", 3],
                    ["broadcast:", "Pin D Off"],
                    ["wait:elapsed:from:", 1]]]],
        "sounds": [{
                "soundName": "meow",
                "soundID": 0,
                "md5": "83c36d806dc92327b9e7049a565c6bff.wav",
                "sampleCount": 18688,
                "rate": 22050,
                "format": ""
            }]
    }]

}

我尝试解析GreenFlag信息,但是当我运行此

> import ast import json from pprint import pprint
> 
> 
> 
> 
> 
> 
> codeInput = [] codeOutput = []
> 
> with open("project.json") as projectFile:
>     codeInput =json.load(projectFile)
> 
> print type(codeInput)
> 
> #pprint(codeInput)
> #print"----"
> 
> #print codeInput["children"]
> 
> scripts = codeInput["children"][0]["scripts"] print type(scripts) for
> items in scripts:
>     print "items",items
> 
> print scripts[2]

我没有得到列表我得到了这个但看起来应该是这样 我的清单

<type 'dict'>
<type 'list'>
items [69, 57, [[u'whenGreenFlag'], [u'broadcast:', u'Pin D On'], [u'wait:elapsed:from:', 3], [u'broadcast:', u'Pin D Off'], [u'wait:elapsed:from:', 1]]]
Traceback (most recent call last):
  File "C:/Dropbox/Private/Scratch2Crumble/projectparser.py", line 46, in <module>
    print scripts[2]
IndexError: list index out of range

我做错了什么?

我刚刚添加了这个额外的文字,以便尝试发布我的任务

2 个答案:

答案 0 :(得分:2)

与字典中的键"scripts"关联的值是包含一个元素的列表。

"scripts": [[69,
            57,
            [["whenGreenFlag"],
                ["broadcast:", "Pin D On"],
                ["wait:elapsed:from:", 3],
                ["broadcast:", "Pin D Off"],
                ["wait:elapsed:from:", 1]]]],

如果"scripts":之后有两个开括号,则表示您有一个包含一个元素的列表,该元素是另一个包含69, 57等的列表。

答案 1 :(得分:2)

这是因为与scripts相关联的值是包含单个元素的列表,该列表是一个列表。 输出格式更好时,您可以看到它:

[
    [
        69,
        57,
        [
            ["whenGreenFlag"],
            ["broadcast:", "Pin D On"],
            ["wait:elapsed:from:", 3],
            ["broadcast:", "Pin D Off"],
            ["wait:elapsed:from:", 1]
        ]
    ]
]

因此,您必须致电scripts[0][2]以获得您想要的内容。

相关问题