JSON From HTTP Print Value With Python

Question:

I’m grabbing JSON from an http link. I can print the entire json string, and I can print all of the key values. What I’m trying to do is to get only certain values based on an ID.

Json output:

{
  "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"
  }
]

As I said I can print all "id" or all "val", but I want to return the "val" for a single "id". I hope that makes sense. Here is code I have to print all "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"])

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

Now I want to print "val" for say "0x0B". That is where I’m stuck.

Answers:

Simply do this:

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

which gives: 3.58 mph