【问题标题】:How do I handle JSON data obtained from request library in Python?如何处理从 Python 中的请求库中获取的 JSON 数据?
【发布时间】:2020-11-05 09:40:04
【问题描述】:

我对使用 API 密钥比较陌生。我已经尝试过 IG Markets API 并获得以下内容。通过使用 r.json(),我设法创建了类型(字典)。我想知道如何处理这种类型的数据并以“更好”的方式访问这些值。

我尝试过使用: 对于 data() 中的键、值: 打印(键,值) 和 数据[“职位”] 但似乎字典只包含一个键。任何帮助表示赞赏!

data = r.json()
print(data)
{'positions': [{'market': {'bid': 1719.59,
                           'delayTime': 0,
                           'epic': '-',
                           'expiry': '-',
                           'high': 1749.95,
                           'instrumentName': 'Sverige30 Cash (100SK)',
                           'instrumentType': 'INDICES',
                           'lotSize': 100.0,
                           'low': 1713.33,
                           'marketStatus': 'TRADEABLE',
                           'netChange': -25.44,
                           'offer': 1721.09,
                           'percentageChange': -1.46,
                           'scalingFactor': 1,
                           'streamingPricesAvailable': True,
                           'updateTime': '22:15:16',
                           'updateTimeUTC': '21:15:16'},
                'position': {'contractSize': 100.0,
                             'controlledRisk': False,
                             'createdDate': '2020/07/13 23:12:53:000',
                             'createdDateUTC': '2020-07-13T21:12:53',
                             'currency': 'USD',
                             'dealId': '',
                             'dealReference': '',
                             'direction': 'BUY',
                             'level': 1720.74,
                             'limitLevel': None,
                             'limitedRiskPremium': None,
                             'size': 5.0,
                             'stopLevel': None,
                             'trailingStep': None,
                             'trailingStopDistance': None}}]}

【问题讨论】:

    标签: python json pandas python-requests json-normalize


    【解决方案1】:
    • 在示例中,只有一条记录,所以我在positions 中创建了一个包含多条记录的示例
    • 我会使用 pandas 来访问所有数据
    import pandas as pd
    
    # create dataframe
    df = pd.json_normalize(data, 'positions')
    
    # display(df)
       market.bid  market.delayTime market.epic market.expiry  market.high   market.instrumentName market.instrumentType  market.lotSize  market.low market.marketStatus  market.netChange  market.offer  market.percentageChange  market.scalingFactor  market.streamingPricesAvailable market.updateTime market.updateTimeUTC  position.contractSize  position.controlledRisk     position.createdDate position.createdDateUTC position.currency position.dealId position.dealReference position.direction  position.level position.limitLevel position.limitedRiskPremium  position.size position.stopLevel position.trailingStep position.trailingStopDistance
    0     1719.59                 0           -             -      1749.95  Sverige30 Cash (100SK)               INDICES           100.0     1713.33           TRADEABLE            -25.44       1721.09                    -1.46                     1                             True          22:15:16             21:15:16                  100.0                    False  2020/07/13 23:12:53:000     2020-07-13T21:12:53               USD                                                       BUY         1720.74                None                        None            5.0               None                  None                          None
    1     1719.59                 0           -             -      1749.95  Sverige30 Cash (100SK)               INDICES           100.0     1713.33           TRADEABLE            -25.44       1721.09                    -1.46                     1                             True          22:15:16             21:15:16                  100.0                    False  2020/07/13 23:12:53:000     2020-07-13T21:12:53               USD                                                       BUY         1720.74                None                        None            5.0               None                  None                          None
    2     1719.59                 0           -             -      1749.95  Sverige30 Cash (100SK)               INDICES           100.0     1713.33           TRADEABLE            -25.44       1721.09                    -1.46                     1                             True          22:15:16             21:15:16                  100.0                    False  2020/07/13 23:12:53:000     2020-07-13T21:12:53               USD                                                       BUY         1720.74                None                        None            5.0               None                  None                          None
    3     1719.59                 0           -             -      1749.95  Sverige30 Cash (100SK)               INDICES           100.0     1713.33           TRADEABLE            -25.44       1721.09                    -1.46                     1                             True          22:15:16             21:15:16                  100.0                    False  2020/07/13 23:12:53:000     2020-07-13T21:12:53               USD                                                       BUY         1720.74                None                        None            5.0               None                  None                          None
    

    data 有多个记录

    data =  {
                'positions': [{
                        'market': {
                            'bid': 1719.59,
                            'delayTime': 0,
                            'epic': '-',
                            'expiry': '-',
                            'high': 1749.95,
                            'instrumentName': 'Sverige30 Cash (100SK)',
                            'instrumentType': 'INDICES',
                            'lotSize': 100.0,
                            'low': 1713.33,
                            'marketStatus': 'TRADEABLE',
                            'netChange': -25.44,
                            'offer': 1721.09,
                            'percentageChange': -1.46,
                            'scalingFactor': 1,
                            'streamingPricesAvailable': True,
                            'updateTime': '22:15:16',
                            'updateTimeUTC': '21:15:16'
                        },
                        'position': {
                            'contractSize': 100.0,
                            'controlledRisk': False,
                            'createdDate': '2020/07/13 23:12:53:000',
                            'createdDateUTC': '2020-07-13T21:12:53',
                            'currency': 'USD',
                            'dealId': '',
                            'dealReference': '',
                            'direction': 'BUY',
                            'level': 1720.74,
                            'limitLevel': None,
                            'limitedRiskPremium': None,
                            'size': 5.0,
                            'stopLevel': None,
                            'trailingStep': None,
                            'trailingStopDistance': None
                        }
                    }, {
                        'market': {
                            'bid': 1719.59,
                            'delayTime': 0,
                            'epic': '-',
                            'expiry': '-',
                            'high': 1749.95,
                            'instrumentName': 'Sverige30 Cash (100SK)',
                            'instrumentType': 'INDICES',
                            'lotSize': 100.0,
                            'low': 1713.33,
                            'marketStatus': 'TRADEABLE',
                            'netChange': -25.44,
                            'offer': 1721.09,
                            'percentageChange': -1.46,
                            'scalingFactor': 1,
                            'streamingPricesAvailable': True,
                            'updateTime': '22:15:16',
                            'updateTimeUTC': '21:15:16'
                        },
                        'position': {
                            'contractSize': 100.0,
                            'controlledRisk': False,
                            'createdDate': '2020/07/13 23:12:53:000',
                            'createdDateUTC': '2020-07-13T21:12:53',
                            'currency': 'USD',
                            'dealId': '',
                            'dealReference': '',
                            'direction': 'BUY',
                            'level': 1720.74,
                            'limitLevel': None,
                            'limitedRiskPremium': None,
                            'size': 5.0,
                            'stopLevel': None,
                            'trailingStep': None,
                            'trailingStopDistance': None
                        }
                    }, {
                        'market': {
                            'bid': 1719.59,
                            'delayTime': 0,
                            'epic': '-',
                            'expiry': '-',
                            'high': 1749.95,
                            'instrumentName': 'Sverige30 Cash (100SK)',
                            'instrumentType': 'INDICES',
                            'lotSize': 100.0,
                            'low': 1713.33,
                            'marketStatus': 'TRADEABLE',
                            'netChange': -25.44,
                            'offer': 1721.09,
                            'percentageChange': -1.46,
                            'scalingFactor': 1,
                            'streamingPricesAvailable': True,
                            'updateTime': '22:15:16',
                            'updateTimeUTC': '21:15:16'
                        },
                        'position': {
                            'contractSize': 100.0,
                            'controlledRisk': False,
                            'createdDate': '2020/07/13 23:12:53:000',
                            'createdDateUTC': '2020-07-13T21:12:53',
                            'currency': 'USD',
                            'dealId': '',
                            'dealReference': '',
                            'direction': 'BUY',
                            'level': 1720.74,
                            'limitLevel': None,
                            'limitedRiskPremium': None,
                            'size': 5.0,
                            'stopLevel': None,
                            'trailingStep': None,
                            'trailingStopDistance': None
                        }
                    }, {
                        'market': {
                            'bid': 1719.59,
                            'delayTime': 0,
                            'epic': '-',
                            'expiry': '-',
                            'high': 1749.95,
                            'instrumentName': 'Sverige30 Cash (100SK)',
                            'instrumentType': 'INDICES',
                            'lotSize': 100.0,
                            'low': 1713.33,
                            'marketStatus': 'TRADEABLE',
                            'netChange': -25.44,
                            'offer': 1721.09,
                            'percentageChange': -1.46,
                            'scalingFactor': 1,
                            'streamingPricesAvailable': True,
                            'updateTime': '22:15:16',
                            'updateTimeUTC': '21:15:16'
                        },
                        'position': {
                            'contractSize': 100.0,
                            'controlledRisk': False,
                            'createdDate': '2020/07/13 23:12:53:000',
                            'createdDateUTC': '2020-07-13T21:12:53',
                            'currency': 'USD',
                            'dealId': '',
                            'dealReference': '',
                            'direction': 'BUY',
                            'level': 1720.74,
                            'limitLevel': None,
                            'limitedRiskPremium': None,
                            'size': 5.0,
                            'stopLevel': None,
                            'trailingStep': None,
                            'trailingStopDistance': None
                        }
                    }
                ]
            }
    

    【讨论】:

    • 太好了,谢谢你的帮助。它对 Pandas 也很有帮助! :)
    【解决方案2】:

    假设您的数据结构可能更大并且可能有多个'positions',您可以循环遍历'positions' 并为每个位置检索size,如下所示:

    for pos in data['positions']:
        size = pos['position']['size']
        print(size)
    

    打印:

    5.0
    

    【讨论】:

      猜你喜欢
      • 2020-08-15
      • 2017-07-29
      • 1970-01-01
      • 1970-01-01
      • 2017-07-17
      • 2021-08-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多