Command_line sensor: Unable to parse outpu as JSON

I’m trying to use a command_line sensor to store two session cookies from a site, but I’m getting the following error:

Unable to parse output as JSON: {'XSRF-TOKEN': 'eyJpdiI6IjhpMXh2VURXSnNzV2xZVllBNkR4Tnc9PSIsInZhbHVlIjoiYUdZMDNzK3E5elJaL1ZBZ3REcmV3V0hnREl1SWJnUkVWSVNSbGlmempjWUJOajdxWmowcGxqTlU4R3ppbHlldGI2UjBCS1Q3REpaeVB1Wk5PSG9BL0NKcVlJSmR5dENNU1JuaTNSa09NU2JFNW5HdjhOamdLZ09SK3dNVTgyNmoiLCJtYWMiOiIzZTdmNTEzZjU5ZjVlMTA0M2VjMGFlMzVhNWQ1NWU1ZjhlY2M2NDgzM2I2MWQxYTM2YWMwYmRhZGY4ODY3MWQ0IiwidGFnIjoiIn0%3D', 'sofia_traffic_session': 'eyJpdiI6IktvWmhtK2xFNEtqSHJUWDZxVGpLL3c9PSIsInZhbHVlIjoiM1RhMDg0MTBoUHJqbFpHREpiaUNMR0RIby9RK29DZmdjWkpia1EzOEVIcGdPRWVwM00raEcwb0RZU3ZXZDh3K1ByeHltNUpPbmVsVk0wWTk2Rjl1c1RmRk02T2tPTUhsc2lPbFBzdEljR3N6L2YrTk9rVzczbDY1VXdDMkZ3U1AiLCJtYWMiOiJiYzNiZjljY2FkNGE4MTFmMDYzMzBiOTc3ODA5ODE1MmM4NjFlODJlNDIwZTEzMDNmNTMyNGJlNmYzNDdlZmU4IiwidGFnIjoiIn0%3D'}

Here’s my code:

command_line:
  - sensor:
       name: sofiatraffic_session
       command: python3 -c "import requests; import urllib; session=requests.get('https://sofiatraffic.bg/bg/public-transport'); print(session.cookies.get_dict())"
       json_attributes_path: "$."
       json_attributes:
#         - XSRF-TOKEN
         - sofia_traffic_session

       value_template: "{{ value_json.sofia_traffic_session }}"

Solved my issue and learned a couple of things in the process.

  • you can’t store more than 255 characters in a state. Instead you should store them in state_attributes
  • single quoted strings in curly braces do not make valid json.
    Here’s the working code:
  - sensor:
       name: sofiatraffic_session
       scan_interval: 7100
       command:  python3 -c "import requests; import json; session=requests.get('https://sofiatraffic.bg/bg/public-transport'); print(json.dumps(session.cookies.get_dict()))" 
       json_attributes:
         - XSRF-TOKEN
         - sofia_traffic_session
1 Like