On startup only : the JSON object must be str, bytes or bytearray, not NoneType

Hi, i always have a template error at startup, the problem is in the first try, the sensor.some_sensor doesnt have a value yet, only after x amount of seconds therefore the value template doesnt work “yet”, in next 5 seconds the error is gone
how can i fix this for my template sensor,so that makes my logbook nicer :slight_smile:

  - platform: template
    sensors:
      callstatus:
        value_template: "{{ (state_attr('sensor.some_sensor', 'data')|from_json).callStatus }}"

error:

2021-05-03 14:55:52 ERROR (MainThread) [homeassistant.helpers.event] Error while processing template: Template("{{ (state_attr('sensor.some_sensor', 'data')|from_json).callStatus }}")
Traceback (most recent call last):
  File "/usr/src/homeassistant/homeassistant/helpers/template.py", line 390, in async_render
    render_result = _render_with_context(self.template, compiled, **kwargs)
  File "/usr/src/homeassistant/homeassistant/helpers/template.py", line 1360, in _render_with_context
    return template.render(**kwargs)
  File "/usr/local/lib/python3.8/site-packages/jinja2/environment.py", line 1090, in render
    self.environment.handle_exception()
  File "/usr/local/lib/python3.8/site-packages/jinja2/environment.py", line 832, in handle_exception
    reraise(*rewrite_traceback_stack(source=source))
  File "/usr/local/lib/python3.8/site-packages/jinja2/_compat.py", line 28, in reraise
    raise value.with_traceback(tb)
  File "<template>", line 1, in top-level template code
  File "/usr/src/homeassistant/homeassistant/helpers/template.py", line 1312, in from_json
    return json.loads(value)
  File "/usr/local/lib/python3.8/json/__init__.py", line 341, in loads
    raise TypeError(f'the JSON object must be str, bytes or bytearray, '
TypeError: the JSON object must be str, bytes or bytearray, not NoneType

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "/usr/src/homeassistant/homeassistant/helpers/template.py", line 506, in async_render_to_info
    render_info._result = self.async_render(variables, strict=strict, **kwargs)
  File "/usr/src/homeassistant/homeassistant/helpers/template.py", line 392, in async_render
    raise TemplateError(err) from err
homeassistant.exceptions.TemplateError: TypeError: the JSON object must be str, bytes or bytearray, not NoneType

You could try checking if the atttribute is not None before setting the value:

 value_template: >
    {% if state_attr('sensor.some_sensor', 'data') != None %}
    {{ (state_attr('sensor.some_sensor', 'data')|from_json).callStatus }}
    {% endif %}
1 Like