这里是python的新手。我试图为每个人迭代所有JSON“组”对象,但有一些困难。这只是一个部分列表(并非所有用户都有组)所以我需要使用try / catch块,这样没有组列表的用户不会导致提前终止。
JSON数据片段:
{
"people": [
{
"person": {
"name": "joe",
"email": "joe@foo.net",
"groups": [
{
"name": "office",
"id": 23
},
{
"name": "mfg",
"id": 93
} ]
},
"person": {
"name": "bill",
"email": "bill@foo.net",
"groups": [
{
"name": "acctg",
"id": 133
},
{
"name": "mgr",
"id": 207
} ]
}
}
]
}
到目前为止,这是我的代码:
jdata = json.loads...
for person in jdata['people']:
for key, val in person.iteritems():
print "key ", key , " is ", val
print val["name"]
print val["email"]
try:
for gkey, gval in val["groups"][0].iteritems():
print "gval: " + gval
except:
foo=1
注意我可以通过执行for gkey...val["groups"][0].iteritems()
打印出组列表中第0个项目的列表,但我真正想要的是遍历每个group
条目的所有person
列表(有些人属于两组,有些人属于10组或更多组)所以没有固定的长度。我怎么能这样做?
答案 0 :(得分:1)
这就是你想要的吗? :
FirstProcessor.Setup(x => x.StartAsync(It.IsAny<TextWriter>())).Throws(new Exception("some exception happened."));
SecondProcessor.Setup(x => x.StartAsync(It.IsAny<TextWriter>())).Returns(Task.FromResult(default(object)));
或更一般地说:
>>> for group in j['people'][0]['person']['groups']:
for k,v in group.items():
print(k,v)
name acctg
id 133
name mgr
id 207