Template: Extracting a value from json

I have a JSON object i have extracted from my vacuum using the following template:

- platform: template
  sensors:
    vacuum_lastrun:
      friendly_name: 'Vacuum last run json object'         
      value_template: >-
        '{{ state_attr('vacuum.rockrobo', 'last_run_stats') }}'

This gives med the following json object as a sensor:

	'{'startTime': 1566334864000, 'endTime': 1566334869000, 'duration': 0, 'area': '0.0', 'errorCode': 0, 'errorDescription': 'No error', 'finishedFlag': False}'

But I’m only really interested in endTime. How would i go ahead and isolate just that one value?

First, it’s not really a JSON object. It’s a Python dictionary converted to a string. Also not sure why you’re putting extra single quotes around it.

The easiest way to get endTime is to create a new template sensor:

- platform: template
  sensors:
    vacuum_lastrun_end:
      friendly_name: 'Vacuum last run end'         
      value_template: >
        {{ state_attr('vacuum.rockrobo', 'last_run_stats').endTime }}

You might also consider adding:

      device_class: timestamp

Thanks, that fixed it. Now I only need to convert it from epoch to human readable :slight_smile:

Not 100% sure, but doesn’t device_class: timestamp do that? If not, then simply use timestamp_local or timestamp_custom.

I got “invalid format” when i used timestamp. I’ll try timestamp local. Thanks

Sorry, I was probably a bit unclear. Also, I did a quick test and device_class: timestamp apparently doesn’t do anything with actual timestamps. Apparently the value needs to be a time string.

Anyway, this should do it:

- platform: template
  sensors:
    vacuum_lastrun_end:
      friendly_name: 'Vacuum last run end'         
      value_template: >
        {{ state_attr('vacuum.rockrobo', 'last_run_stats').endTime | timestamp_local }}

Or you could use timestamp_custom(format_string) in place of timestamp_local if you want to control the format of the resulting time string. See Time formatting.