#I am getting stuck parsing json in a
1 messages · Page 1 of 1 (latest)
this is in templates it works:
{% set value_json = '{"cars":[{"car_id":"789","user_name":"John","mileage_allowance":"150","activation_status":"active","tags":["555555","111111","222222"]},{"car_id":"987","user_name":"Jane","mileage_allowance":"200","activation_status":"active","tags":["777777"]}]}' %}
{% set cars_json = value_json | from_json %}
{{ cars_json.cars|length }}
here is the plain json:
{
"cars": [
{
"car_id": "789",
"user_name": "John",
"mileage_allowance": "150",
"activation_status": "active",
"tags": ["555555", "111111", "222222"]
},
{
"car_id": "987",
"user_name": "Jane",
"mileage_allowance": "200",
"activation_status": "active",
"tags": ["777777"]
}
]
}
your code should output 2
{{ cars_json.cars | selectattr('car_id', 'eq', '789') | list | first }}
for your next question
or
{{ cars_json.cars | selectattr('user_name', 'eq', 'John') | list | first }}
whatever you want to find
that part i think i got. i wanted to loop through each one to get to do that so I needed the count, but yes that's my next question
I am trying to use this to set a variable to be used in a script. does it not work with multilines? this is what I have:
- variables:
Count: |
{% set value_json = cars_response['stdout'] %}
{% set cars_json = value_json | from_json | default({}) %}
{{cars_json.cars|length}}
Count_json: "{{ cars_response['stdout'] | from_json | default({}) |count}}"
json: "{{ cars_response['stdout'] | from_json | default({}) }}"
- service: persistent_notification.create
data:
title: "count:"
notification_id: "count"
message: |
{% set value_json = cars_response['stdout'] %}
{% set cars_json = value_json | from_json | default({}) %}
{{cars_json.cars|length}}
the count variable (multiline) does not work (checked in a different notification) the count_json one does work but I don't know where to put .cars, the notification without the variable works.
not really sure what you're asking
I want to use variables so other parts of the script can access the count. the count: | part does not have any value.
Even though it does when I use the exact same template in a persistent notification.
- variables:
count_json: >
{{ cars_response['stdout'] | from_json | default({}) }}
cars_json: >
{{ count_json.cars }}
count: >
{{ cars_json | length }}
- service: persistent_notification.create
data:
title: "count:"
notification_id: "count"
message: "{{ count }}"