Parsing JSON file with missing attributes

Hi there

I want to parse and summarize data from a JSON file:

{
  "state": "success",
  "message": "successfully fetched collection",
  "timings": {
    "login": 0.34564,
    "load": 0.93459,
    "login_perc": 78.02334204443939,
    "load_perc": 12.1025787703513126
  },
  "count": 4,
  "data": [
    {
      "time": 1682096400000,
      "rx_bytes": 131206,
      "tx_bytes": 224112,
      "user": "user_1",
      "o": "user",
      "oid": "user_1"
    },
    {
      "time": 1682100000000,
      "rx_bytes": 258959.9090909091,
      "tx_bytes": 696057,
      "user": "user_1",
      "o": "user",
      "oid": "user_1"
    },
    {
      "time": 1682164800000,
      "user": "user_1",
      "o": "user",
      "oid": "user_1"
    },
    {
      "time": 1682179200000,
      "rx_bytes": 221165,
      "tx_bytes": 699866,
      "user": "user_1",
      "o": "user",
      "oid": "user_1"
    }
  ]
}

I want to have the sum of the attributes “rx_bytes” and “tx_bytes” with
{{ value_json.data | sum(attribute='rx_bytes') }}

All is fine when all objects have these attributes. But it can happen that the attributes are missing.

UndefinedError: 'dict object' has no attribute 'rx_bytes'

Is there a way to ignore the objects with no attributes?

Thanks for your support!

{{ value_json.data | selectattr('rx_bytes','defined') | sum(attribute='rx_bytes') }}

wow!!
thanks for this!