0

我需要阅读一条 JSON 消息,其中包含一个名为“derivedFrom”的键。它的值可能具有以下形式:

Case 1. "derivedFrom": "id1"

或这个:

Case 2. "derivedFrom": ["id1", "id2", "id3"]

我需要做的是非常基本的事情:读取值并循环它们。现在我正在这样做:

#line contains JSON string
data = json.loads(line)
# ...
derivedIds = data['derivedFrom']
for deid in derivedIds:
# ...

这适用于案例 2,但对于案例 1,它会遍历 id“id1”的单个字符,这显然不是我需要的。

如何修改上面的块以正确处理这两种情况?谢谢

4

3 回答 3

1

如果您知道derivedFrom 的值将始终是一个列表或一个值(即,不是字典):

#line contains JSON string
data = json.loads(line)
# ...
derivedIds = data['derivedFrom']
if not isinstance(derivedIds, list):
    derivedIds = [derivedIds]
for deid in derivedIds:

它来自 JSON 的事实简化了问题,因为它极大地限制了您必须担心的数据类型的数量。

于 2012-11-21T18:10:59.007 回答
0

作为原始示例:

#line contains JSON string
data = json.loads(line)
# ...
derivedIds = data['derivedFrom']
if isinstance(derivedIds, basestring):
   #.... 
else:
    for deid in derivedIds:
    # ...
于 2012-11-21T18:18:04.440 回答
0

str/unicode您可以使用没有__iter__属性的事实,而listssetsdicts做。

#!/usr/bin/env python

import json

case1 = '{"derivedFrom": "id1"}'

case2 = '{"derivedFrom": ["id1", "id2", "id3"]}'

def parse(line):
    data = json.loads(line)
    if not(hasattr(data["derivedFrom"], "__iter__")):
        print "Converting %s to list" % type(data["derivedFrom"])
        data["derivedFrom"] = [data["derivedFrom"]]
    print "data['derivedFrom']: %s, of type %s" % (data["derivedFrom"], type(data["derivedFrom"]))

if __name__ == "__main__":
    parse(case1)
    parse(case2)

虽然,如果可能的话,我更愿意修改发送该 JSON 的任何内容以确保发送列表(尝试使其发送'{"derivedFrom": ["id1"]}'

于 2012-11-21T17:59:48.930 回答