【问题标题】:Parsing JSON string in Python在 Python 中解析 JSON 字符串
【发布时间】:2018-01-14 08:48:44
【问题描述】:

我是 Python 新手,请您耐心等待!

在下面的输出字符串中,我需要获取最新的价格(根据时间戳确定),其中 type = 'bid'。请建议我如何将输出读入 JSON 并读取最新价格

{"dollar_pound":[
{"type":"ask","price":0.01769341,"amount":1.10113151,"tid":200019988,"timestamp":1515919171},
{"type":"ask","price":0.017755,"amount":3.95681783,"tid":200019987,"timestamp":1515919154},
{"type":"bid","price":0.01778859,"amount":3.7753814,"tid":200019986,"timestamp":1515919152},
{"type":"ask","price":0.017755,"amount":0.01216145,"tid":200019985,"timestamp":1515919147},
{"type":"ask","price":0.017755,"amount":0.05679142,"tid":200019984,"timestamp":1515919135}]}

我试过了,但没有成功

parsed_json = json.loads(request.text)
price = parsed_json['price'][0]

【问题讨论】:

  • “在 Python 中解析 JSON”的 [internet] 搜索结果显示了什么?当然,您不是唯一在 Python 中解析 JSON 的人。而且,一旦解析了 JSON,下一步是什么?这(导航字典/列表)也可能包含在现有文档中,例如教程。
  • HTTP 请求的输出如上图。您还有其他要求吗?
  • 是的,tldr; “你尝试了什么?尝试过的东西有什么'不起作用'?”什么都没试过?好吧,那么目前没有问题 ..只有一个任务。祝你好运!
  • parsed_json = json.loads(request.text) price = parsed_json['price'][0]
  • parsed_json['price'] 返回无。为什么? 迭代列表(如教程中所述)在这里有什么用处?

标签: json python-3.x


【解决方案1】:

我认为这可能是您想要的 - 这是一个简短的脚本,用于获取“bid”类型的最新价格:

# Here's a few more test cases for bid prices to let you test out your script
parsed_json = {"dollar_pound":[
{"type":"ask","price":0.01769341,"amount":1.10113151,"tid":200019988,"timestamp":1515919171},
{"type":"ask","price":0.017755,"amount":3.95681783,"tid":200019987,"timestamp":1515919154},
{"type":"bid","price":0.01778859,"amount":3.7753814,"tid":200019986,"timestamp":1515919152},
{"type":"bid","price":0.01542344,"amount":3.7753814,"tid":200019983,"timestamp":1715929152},
{"type":"bid","price":0.023455,"amount":3.7753814,"tid":200019982,"timestamp":1515919552},
{"type":"ask","price":0.017755,"amount":0.01216145,"tid":200019985,"timestamp":1515919147},
{"type":"ask","price":0.017755,"amount":0.05679142,"tid":200019984,"timestamp":1515919135}]}

# To get items of type "bid"
def get_bid_prices(parsed_json):
    return filter(lambda x: x["type"] == "bid", parsed_json)

# Now, we want to get the latest "bid" price, i.e. the largest number in the "timestamp" field
latest_bid_price = max(get_bid_prices(parsed_json["dollar_pound"]), key=lambda x: x["timestamp"])

# Your result will be printed here
print(latest_bid_price) # {"type":"bid","price":0.01542344,"amount":3.7753814,"tid":200019983,"timestamp":1715929152}

【讨论】:

    【解决方案2】:

    对于所有像我一样苦苦挣扎的好人,我想为他们分享答案。

    json_data = json.loads (req.text)
    for x in json_data['dollar_pound']:
        print (x['price'])
    

    【讨论】:

      猜你喜欢
      • 2021-10-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多