已成功解析此深度嵌套的JSON lis

2024-03-29 12:52:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我以以下格式返回了一个JSON对象:

[[[13,
   u'Arsenal',
   [[[[u'goal', u'openplay', u'header', [1]],
      [u'goal', u'openplay', u'leftfoot', [1]],
      [u'goal', u'openplay', u'rightfoot', [3]],
      [u'goal', u'owngoal', u'rightfoot', [1]],
      [u'miss', u'corner', u'header', [2]],
      [u'miss', u'corner', u'leftfoot', [3]],
      [u'miss', u'corner', u'rightfoot', [2]],
      [u'miss', u'crossedfreekick', u'rightfoot', [2]],
      [u'miss', u'directfreekick', u'leftfoot', [1]],
      [u'miss', u'openplay', u'header', [2]],
      [u'miss', u'openplay', u'leftfoot', [16]],
      [u'miss', u'openplay', u'rightfoot', [23]]]]]]]]

当我使用此代码时:

for match in responser: 
    for num_events, team, events in match:
        regex = {tuple(sub[:3]): sub[3][0] for y in events[0] for sub in y}

我得到上面作为字典返回的嵌套列表,其中的键由从上面的文本值派生的元组组成,这些值也从上面的嵌套列表派生。你知道吗

然后我有了这个稍微不同的数据结构(同样是JSON):

[[[13,
   u'Arsenal',
   [[6.125,
     [[u'assist', u'cross', [3]],
      [u'normal', u'cross', [198]],
      [u'normal', u'longball', [326]],
      [u'assist', u'short', [5]],
      [u'normal', u'short', [4726]],
      [u'assist', u'throughball', [1]],
      [u'normal', u'throughball', [35]]]]]]]]

据我所知,这和第一组嵌套列表(除了每个列表有两个而不是三个文本元素)之间的唯一区别是值“6.125”,它包含在一组嵌套括号之间。因此,在我看来,以下代码应该允许我解析第二个数据结构:

for match in responser: 
    for num_events, team, events in match:
        regex = {tuple(sub[:2]): sub[2][0] for y in events[0] for sub in y}

但是,这将返回以下错误:

exceptions.TypeError: 'float' object is not iterable

有人能告诉我什么是我的误解和语法来纠正我的问题吗?你知道吗


Tags: injson列表formatcheventsheadernormal