如何将JSON数据(从API)转换为python数据?

时间:2018-08-02 14:33:40

标签: python json api

嘿,我正在准备从API股票市场获取数据。

import zmq
context = zmq.Context()
socket = context.socket(zmq.SUB)
print("Recibo mensajes del servidor...")
socket.connect("tcp://XXXXXXXXXXXXXXXXXX")
socket.setsockopt_string(zmq.SUBSCRIBE, u'')
while True:
    JSON = socket.recv_json()
    print(JSON)

接收这样的数据:

{'X': {'MDReqId': 'HUB22_1533207696768', 'MDIncGrp': [{'offer': {'OrderID': 
'', 'SettlType': '3', 'MDEntrySeller': '', 'Precio': '435', 
'MDEntryPositionNo': '1', 'SettlDate': '', 'MDEntrySize': 2000.0, 
'MDUpdateAction': '2', 'MDEntryTime': '10:37:56', 'Symbol': 'BA.C', 
'MDEntryBuyer': '', 'NumberOfOrders': '', 'MDEntryDate': '20180802'}}], 
'MDBookType': 2}}
{'X': {'MDReqId': 'HUB22_1533207696768', 'MDIncGrp': [{'bid': {'OrderID': '', 
'SettlType': '3', 'MDEntrySeller': '', 'Precio': '410', 'MDEntryPositionNo': 
'2', 'SettlDate': '', 'MDEntrySize': 24.0, 'MDUpdateAction': '0', 
'MDEntryTime': '10:37:56', 'Symbol': 'BA.C', 'MDEntryBuyer': '200', 
'NumberOfOrders': '', 'MDEntryDate': '20180802'}}, {'offer': {'OrderID': '', 
'SettlType': '3', 'MDEntrySeller': '046', 'Precio': '450', 
'MDEntryPositionNo': '1', 'SettlDate': '', 'MDEntrySize': 2000.0, 
'MDUpdateAction': '0', 'MDEntryTime': '10:37:56', 'Symbol': 'BA.C', 
'MDEntryBuyer': '200', 'NumberOfOrders': '', 'MDEntryDate': '20180802'}}, 
{'bid': {'OrderID': '', 'SettlType': '3', 'MDEntrySeller': '046', 'Precio': 
'433', 'MDEntryPositionNo': '1', 'SettlDate': '', 'MDEntrySize': 10.0, 
'MDUpdateAction': '0', 'MDEntryTime': '10:37:56', 'Symbol': 'BA.C', 
'MDEntryBuyer': '262', 'NumberOfOrders': '', 'MDEntryDate': '20180802'}}], 
'MDBookType': 3}}

我的问题是:

如何将JSON数据(从API)转换为python数据?

2 个答案:

答案 0 :(得分:0)

您从recv_json获得的结果已经是内置的Python类型(dict)。因此,您可以执行以下操作:

JSON['x']

答案 1 :(得分:0)

您已经拥有JSON(嗯,一个Python dict,但是Python人士认为它们是同一回事)!

运行此实验:

while True:
    json = socket.recv_json()

    print(json['X'])

    x = json['X']  # now `x` is the "same" as json['X']

    print(x['MDReqId'])  # this is equivalent to print(json['X']['MDReqId'])

    md_req_id = x['MDReqId']
    print(md_req_id)  # should output `HUB22_1533207696768`