Python json command line sensor not working

Hi guys,

I am trying for days now to make an easy command_line sensor example working. Googled a lot.
The python script looks this:

#!/usr/bin/python3
print({"date": "04-10-2023","milliseconds_since_epoch": 1681154879211,"time": "07:27:59 PM"})

The sensor in configuration.yaml looks this:

sensor:
  - platform: command_line
    name: JSON time
    json_attributes:
      - date
      - milliseconds_since_epoch
    command: "python3 /config/python_scripts/datetime.py"
    value_template: "{{ value_json.time }}"

Now I got two errors:

Template variable error: 'value_json' is undefined when rendering '{{ value_json.time }}'
Unable to parse output as JSON: {'date': '04-10-2023', 'milliseconds_since_epoch': 1681154879211, 'time': '07:27:59 PM'}

No idea what could be the problem. Unfortunately in the example, the python script code is missing:
https://www.home-assistant.io/integrations/sensor.command_line/#usage-of-json-attributes-in-command-output

Try this, I have seen cases where a reserved word causes issues, the error not being descriptive enough

{{ value_json['time'] }}

Thanks for that! I dont really understand why, but the first error is now solved. That would be an error in the example in the documentation!

Now there is still the second error:

Unable to parse output as JSON: {'date': '04-10-2023', 'milliseconds_since_epoch': 1681154879211, 'time': '07:27:59 PM'}

I am sure that this is valid JSON!

Probably the same reason with date… I have no access to my system for a few days so cannot test.
You could try to put the json_attribtues between quotes

I asked ChatGPT and voila, got a working solution:

#!/usr/bin/python3
import json
data = {"date": "04-10-2023","milliseconds_since_epoch": 1681154879211,"time": "07:27:59 PM"}
json_string = json.dumps(data)
print(json_string)

Great but what did you change in the sensor?
EDIT: forget the question, just noticed you handled the data differently …

And a note

Is giving poor results where a vast majority is wrong so you won’t get support when you use Chatgpt as a basis, there is a separate post on that

Thanks, I will check the post on ChatGPT. I was just amazed that it had the correct solution for me. By the way, I got an other great advice from it:

sensor:
  - platform: command_line
    name: JSON time
    command: "python3 /config/python_scripts/datetime.py"
    json_attributes:
      - date
      - milliseconds_since_epoch
      - time
    value_template: "{{ value_json | tojson }}"

With this, I can access all three JSON attributes, which was not possible before. I think this is the correct solution for the command_line example in the documentation.

OK, good info :slight_smile: