【问题标题】:Extracting data json python提取数据json python
【发布时间】:2019-05-06 16:03:29
【问题描述】:

我尝试从中解析 json:

{
  "lastUpdateId": 78772216,
  "bids": [
    [
      "0.00000421",
      "133090.00000000"
    ],
    [
      "0.00000420",
      "345637.00000000"
    ],
    [
      "0.00000419",
      "84680.00000000"
    ],
    [
      "0.00000418",
      "127899.00000000"
    ],
    [
      "0.00000417",
      "175359.00000000"
    ]
  ],
  "asks": [
    [
      "0.00000422",
      "324731.00000000"
    ],
    [
      "0.00000423",
      "323497.00000000"
    ],
    [
      "0.00000424",
      "86010.00000000"
    ],
    [
      "0.00000425",
      "207321.00000000"
    ],
    [
      "0.00000426",
      "161378.00000000"
    ]
  ]
}

但总是有一些问题。

我试试这个:

from binance.client import Client
import json

api_key = "..."
api_secret = "..."
client = Client(api_key, api_secret)

depth = client.get_order_book(symbol='QKCBTC', limit=5)


file = json.dumps(depth, indent=2)


for i in file["asks"]:
    print(i[1])

我尝试转储、加载、加载而不是“转储”。

错误:

转储 - 类型错误:字符串索引必须是整数;

loads - raise TypeError(f'JSON对象必须是str, bytes or bytearray, ' TypeError: JSON对象必须是str, bytes or bytearray, not dict;

load - AttributeError: 'dict' object has no attribute 'read';

dump - 类型错误:dump() 缺少 1 个必需的位置参数:'fp';

感谢您的解决方案。

【问题讨论】:

  • 错误告诉你你有一本字典——你不需要从 json 反序列化,因为这已经完成了。
  • 您不需要使用json.dumps,因为您已经有了字典。调用print(depth['asks']) 将打印数字列表。
  • 谢谢,你解决了我的问题;D

标签: python json


【解决方案1】:

json.dumps()是一个将dict对象转换为JSON字符串并返回的函数,所以返回的是字符串对象。

现在有两种情况,

  1. 如果client.get_order_book()返回一个dict,那么你不需要对数据做任何事情,你可以遍历asks

  2. 如果 client.get_order_book() 返回一个 json 字符串,那么您只需使用 json.loads() 将其解析为 dict

【讨论】:

    猜你喜欢
    • 2022-11-21
    • 1970-01-01
    • 1970-01-01
    • 2023-04-07
    • 1970-01-01
    • 2015-06-26
    • 2021-11-24
    • 2017-04-16
    • 2020-05-06
    相关资源
    最近更新 更多