Template for unlabeled JSON response from API

Hi, I’m trying to parse data from this api (https://data.cdc.gov/resource/2ew6-ywp6.json?county_names=Kings). The top level json element is unlabeled, and I’m struggling to figure out how to access the desired elements.

Here’s the general structure of my sensor, which works so long as I take the entire API response as a single element:

- platform: command_line                                                      
    name: "COVID WasteWater"
    scan_interval: 60
    command: >
      echo "{ \"data\":" $(
      curl -s https://data.cdc.gov/resource/2ew6-ywp6.json?county_names=Kings              
      ) "}"
    value_template: >
      {{ value_json }}

But, I’d like to use a value template that ingests each API response separately, and allows me to access the json attributes, like this:

- platform: command_line                                                      
    name: "COVID WasteWater"
    scan_interval: 60
    command: >
      echo "{ \"data\":" $(
      curl -s https://data.cdc.gov/resource/2ew6-ywp6.json?county_names=Kings              
      ) "}"
    value_template: >
      {{ value_json[0] }}
    json_attributes:
      - wwtp_id
      - date_end
      - detect_prop_15d
      - percentile

{{ value_json[0] }} works in the dev_tools template, but doesn’t retrieve any data when actually configuered in the sensor. I’ve also tried {{ value_json[0] | default }} based on this post.

That’s most likely because that JSON substruct is too large - you can only store up to 255 characters in a sensor state value.

Is there a particular reason you are using a command_line sensor for this? I would recommend using the rest integration instead. This should give you the first entry of the array in the response:

rest:
  - resource: https://data.cdc.gov/resource/2ew6-ywp6.json?county_names=Kings
    scan_interval: 60
    sensor:
      - name: "COVID WasteWater"
        value_template: "OK"
        json_attributes_path: "$.[0]"
        json_attributes:
          - wwtp_id
          - date_end
          - detect_prop_15d
          - percentile

However, from the JSON respones I don’t quite understand what you want your sensor to capture because the first entry in the array appears to provide data collected back in June 2022? Apparently you can manually define an end_date URL parameter to get the latest data point (https://data.cdc.gov/resource/2ew6-ywp6.json?county_names=Kings&date_end=2022-12-21), but I can’t see a way to find that latest date.

1 Like

This worked perfectly, thanks so much – I wasn’t aware of the rest integraton!

And for posterity, the solution to getting a single data point was using the SoQL option with an $order parameter: https://data.cdc.gov/resource/2ew6-ywp6.json?$where=county_names=%22Kings%22&$order=date_end%20DESC%20&$limit=1

1 Like