在市场和参赛者的嵌套结构中解析价格?

时间:2018-02-12 14:56:54

标签: python json for-loop

我对编程很新,我正试着解析json。具体来说,我正在使用描述足球博彩市场的字符串,并且包含(以及其他许多)个人匹配(marketId)的值,每个可能结果的子值(主页/客场/平局)(selectionId),以及进一步您可以支持(价格)的价格的子价值。

我已经通过json.loads运行我的代码,并且我已经使用了它,我已将其分配给变量“output”。

[{"jsonrpc":"2.0","result":[{"marketId":"1.139185909","isMarketDataDelayed":true,"status":"OPEN","betDelay":0,"bspReconciled":false,"complete":true,"inplay":false,"numberOfWinners":1,"numberOfRunners":3,"numberOfActiveRunners":3,"lastMatchTime":"2018-02-12T10:56:09.726Z","totalMatched":645229.98,"totalAvailable":1039329.11,"crossMatching":true,"runnersVoidable":false,"version":2045792715,"runners":[{"selectionId":55190,"handicap":0.0,"status":"ACTIVE","lastPriceTraded":1.4,"totalMatched":0.0,"ex":{"availableToBack":[{"price":1.39,"size":56703.76}],"availableToLay":[{"price":1.4,"size":35537.54}],"tradedVolume":[]}},{"selectionId":1703,"handicap":0.0,"status":"ACTIVE","lastPriceTraded":11.0,"totalMatched":0.0,"ex":{"availableToBack":[{"price":10.5,"size":3592.64}],"availableToLay":[{"price":11.0,"size":5913.05}],"tradedVolume":[]}},{"selectionId":58805,"handicap":0.0,"status":"ACTIVE","lastPriceTraded":5.3,"totalMatched":0.0,"ex":{"availableToBack":[{"price":5.2,"size":9136.62}],"availableToLay":[{"price":5.3,"size":5361.48}],"tradedVolume":[]}}]},{"marketId":"1.139782182","isMarketDataDelayed":true,"status":"OPEN","betDelay":0,"bspReconciled":false,"complete":true,"inplay":false,"numberOfWinners":1,"numberOfRunners":3,"numberOfActiveRunners":3,"lastMatchTime":"2018-02-12T10:25:33.842Z","totalMatched":1715.46,"totalAvailable":39526.8,"crossMatching":true,"runnersVoidable":false,"version":2044817355,"runners":[{"selectionId":18567,"handicap":0.0,"status":"ACTIVE","lastPriceTraded":2.3,"totalMatched":0.0,"ex":{"availableToBack":[{"price":2.22,"size":148.27}],"availableToLay":[{"price":2.32,"size":10.1}],"tradedVolume":[]}},{"selectionId":62683,"handicap":0.0,"status":"ACTIVE","lastPriceTraded":3.85,"totalMatched":0.0,"ex":{"availableToBack":[{"price":3.8,"size":76.9}],"availableToLay":[{"price":3.9,"size":20.57}],"tradedVolume":[]}},{"selectionId":58805,"handicap":0.0,"status":"ACTIVE","lastPriceTraded":3.25,"totalMatched":0.0,"ex":{"availableToBack":[{"price":3.2,"size":21.19}],"availableToLay":[{"price":3.5,"size":85.41}],"tradedVolume":[]}}]}], "id":1}]

我正在尝试提取'marketId'的值,然后是'selectionId'和'price'的相应子值,它们应该如下所示:

1.139185909 (marketId 0)
55190       (selectionId 0 under the first market)
1.39        (selectionId 0's back price)
1.4         (selectionId 0's lay price)
1703        (selectionId 1 under the first market)
10.5        (selectionId 1's back price)
11          (selectionId 1's lay price)
58805       (selectionId 2 under the first market)
5.2         (selectionId 2's back price)
5.3         (selectionId 2's lay price)
1.139782182 (marketId 1)
18567       (selectionId 0 under the second market)
2.22        (selectionId 0's back price)
2.32        (selectionId 0's lay price)
62683       (selectionId 1 under the second market)
cont...

我用for循环来打印这些值:

for i in output[0]['result']:
    print(i.get('marketId'))
    for j in output[0]['result'][0]['runners']:
        print(j.get('selectionId'))
        for k in output[0]['result'][0]['runners'][0]['ex']['availableToBack']:
            print(k.get('price'))
            for l in output[0]['result'][0]['runners'][0]['ex']['availableToLay']:
                print(l.get('price'))

当我运行它时,它会返回:

1.139185909  
55190        
1.39         
1.4          
1703         
1.39         
1.4
58805
1.39
1.4
1.139782182
55190
1.39
1.4
1703
1.39
1.4
58805
1.39
1.4

这里的marketId值没问题,但是当我尝试返回其他嵌套值时,程序会一直返回它遇到的第一组值。我似乎无法在任何地方找到答案 - 我怎样才能让它返回正确的值?

1 个答案:

答案 0 :(得分:1)

您正在指示每个列表的第一个元素。您的for循环确实每次都可以访问其他对象,但是您的嵌套循环会忽略这些元素。

使用时

for i in output[0]['result']:

i被绑定到'result'列表中的每个元素,逐个打印出marketId值。

但是你的下一个循环,然后忽略除了第一个这些词典之外的所有:

for j in output[0]['result'][0]['runners']:

这里,output[0]['result'][0]是外环中绑定到i的第一个对象。因此,对于每个i,您忽略该对象(除了使用'markedId'键),然后只查看第一个此类对象的运行器。

使用'runners'的{​​{1}}键代替:

i

for i in output[0]['result']: print(i.get('marketId')) for j in i['runners']: # i is the object from the outer loop print(j.get('selectionId')) # ... 首先绑定到i,然后绑定到output[0]['result'][0]等,所以output[0]['result'][1]现在跟随并允许您处理正确的子结构。

对每个嵌套级别都这样做; i['runners']是另一个字典,因此请使用j

您不需要为j['ex']['availableToBack']for条目嵌套availableToBack循环,availableToLay只包含一个字典对象,并且它具有这两个键(参考列表)。您无需为ex中的每个价格生成所有availableToLay价格的输出。

如果您完全打印Python数据结构,则更容易看到所有这些:

availableToBack

如果使用更具描述性的名称,您的代码将更具可读性:

>>> pprint(output)
[{'id': 1,
  'jsonrpc': '2.0',
  'result': [{'betDelay': 0,
              'bspReconciled': False,
              'complete': True,
              'crossMatching': True,
              'inplay': False,
              'isMarketDataDelayed': True,
              'lastMatchTime': '2018-02-12T10:56:09.726Z',
              'marketId': '1.139185909',
              'numberOfActiveRunners': 3,
              'numberOfRunners': 3,
              'numberOfWinners': 1,
              'runners': [{'ex': {'availableToBack': [{'price': 1.39,
                                                       'size': 56703.76}],
                                  'availableToLay': [{'price': 1.4,
                                                      'size': 35537.54}],
                                  'tradedVolume': []},
                           'handicap': 0.0,
                           'lastPriceTraded': 1.4,
                           'selectionId': 55190,
                           'status': 'ACTIVE',
                           'totalMatched': 0.0},
                          {'ex': {'availableToBack': [{'price': 10.5,
                                                       'size': 3592.64}],
                                  'availableToLay': [{'price': 11.0,
                                                      'size': 5913.05}],
                                  'tradedVolume': []},
                           'handicap': 0.0,
                           'lastPriceTraded': 11.0,
                           'selectionId': 1703,
                           'status': 'ACTIVE',
                           'totalMatched': 0.0},
                          {'ex': {'availableToBack': [{'price': 5.2,
                                                       'size': 9136.62}],
                                  'availableToLay': [{'price': 5.3,
                                                      'size': 5361.48}],
                                  'tradedVolume': []},
                           'handicap': 0.0,
                           'lastPriceTraded': 5.3,
                           'selectionId': 58805,
                           'status': 'ACTIVE',
                           'totalMatched': 0.0}],
              'runnersVoidable': False,
              'status': 'OPEN',
              'totalAvailable': 1039329.11,
              'totalMatched': 645229.98,
              'version': 2045792715},
             {'betDelay': 0,
              'bspReconciled': False,
              'complete': True,
              'crossMatching': True,
              'inplay': False,
              'isMarketDataDelayed': True,
              'lastMatchTime': '2018-02-12T10:25:33.842Z',
              'marketId': '1.139782182',
              'numberOfActiveRunners': 3,
              'numberOfRunners': 3,
              'numberOfWinners': 1,
              'runners': [{'ex': {'availableToBack': [{'price': 2.22,
                                                       'size': 148.27}],
                                  'availableToLay': [{'price': 2.32,
                                                      'size': 10.1}],
                                  'tradedVolume': []},
                           'handicap': 0.0,
                           'lastPriceTraded': 2.3,
                           'selectionId': 18567,
                           'status': 'ACTIVE',
                           'totalMatched': 0.0},
                          {'ex': {'availableToBack': [{'price': 3.8,
                                                       'size': 76.9}],
                                  'availableToLay': [{'price': 3.9,
                                                      'size': 20.57}],
                                  'tradedVolume': []},
                           'handicap': 0.0,
                           'lastPriceTraded': 3.85,
                           'selectionId': 62683,
                           'status': 'ACTIVE',
                           'totalMatched': 0.0},
                          {'ex': {'availableToBack': [{'price': 3.2,
                                                       'size': 21.19}],
                                  'availableToLay': [{'price': 3.5,
                                                      'size': 85.41}],
                                  'tradedVolume': []},
                           'handicap': 0.0,
                           'lastPriceTraded': 3.25,
                           'selectionId': 58805,
                           'status': 'ACTIVE',
                           'totalMatched': 0.0}],
              'runnersVoidable': False,
              'status': 'OPEN',
              'totalAvailable': 39526.8,
              'totalMatched': 1715.46,
              'version': 2044817355}]}]

输出:

for response in output:  # loop over the JSONRPC responses
    for market in response['result']:   # each is a market
        print(market['marketId'])
        for runner in market['runners']:
            print(runner['selectionId'])
            for entry in runner['ex']['availableToBack']:
                print(entry['price'])
            for entry in runner['ex']['availableToLay']:
                print(entry['price'])