使用 Python 从 HTTP 打印值的 JSON

问题描述 投票:0回答:1

提前感谢您的帮助 - 我已经搜索了几个小时了。

如果我使用了错误的术语,请原谅我。

我正在从 http 链接获取 JSON。我可以打印整个 json 字符串,并且可以打印所有键值。我想做的是根据 ID 仅获取某些值。

Json 输出:

{
  "common_list": [

  {
    "id": "0x0B",
    "val": "3.58 mph"
  },
  {
    "id": "0x0C",
    "val": "5.82 mph"
  },
  {
    "id": "0x19",
    "val": "15.88 mph"
  },
  {
    "id": "0x15",
    "val": "519.26 W/m2"
  },
  {
    "id": "0x17",
    "val": "4"
  },
  {
    "battery": "5",
    "id": "0x0A",
    "val": "243"
  }
]

正如我所说,我可以打印所有“id”或所有“val”,但我想返回单个“id”的“val”。我希望这是有道理的。这是我必须打印所有“id”的代码:

import json
from urllib.request import urlopen

url = 'http://ecowitt/get_livedata_info'
resp = urlopen(url)
data = json.loads(resp.read())
dicts = data['common_list']

for dict in dicts:
    print(dict["id"])

输出: 0x02 0x07 3 0x03 0x0B 0x0C 0x19 0x15 0x17 0x0A

现在我想打印“val”来表示“0x0B”。这就是我被困住的地方。谢谢!

json python-3.x http key-value-store
1个回答
0
投票

只需这样做:

dicts = [
  {"id": "0x0B", "val": "3.58 mph"},
  {"id": "0x0C", "val": "5.82 mph"},
  {"id": "0x19", "val": "15.88 mph"},
  {"id": "0x15", "val": "519.26 W/m2"},
  {"id": "0x17", "val": "4"},
  {"battery": "5", "id": "0x0A", "val": "243"}
]

target_id = '0x0B'

for item in dicts:
    if item.get("id") == target_id:
        print(item.get("val"))
        break

给出:3.58 mph

© www.soinside.com 2019 - 2024. All rights reserved.