Example to parse values from JSON response to HTTP Request (#1914)

* Example to parse values from JSON response to HTTP Request

* Make the example less generic

Thanks @jesserockz 
https://discord.com/channels/429907082951524364/943548559289122837/943611047728799785

* Update http_request.rst

* Update http_request.rst

* Update http_request.rst
This commit is contained in:
H. Árkosi Róbert 2022-03-12 19:27:48 +01:00 committed by GitHub
parent 044a7c2704
commit 7bfbc6f228
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -174,8 +174,8 @@ Templatable values
return id(my_sensor).state;
Body in JSON format (syntax 1)
******************************
POST Body in JSON format (syntax 1)
***********************************
**Note:** all values of the map should be a strings.
It's impossible to send ``boolean`` or ``numbers`` with this syntax.
@ -194,8 +194,8 @@ It's impossible to send ``boolean`` or ``numbers`` with this syntax.
# Will send:
# {"key": "42.0", "greeting": "Hello World"}
Body in JSON format (syntax 2)
******************************
POST Body in JSON format (syntax 2)
***********************************
**Note:** use this syntax to send ``boolean`` or ``numbers`` in JSON.
@ -217,6 +217,29 @@ as seen below.
# Will send:
# {"key": 42.0, "greeting": "Hello World"}
GET values from a JSON body response
************************************
Assuming that the server returns a response in a JSON object over HTTP similar to this:
``{"status":"play","vol":"42","mute":"0"}``
If you want to retrieve the value for the ``vol`` key and assign it to a template ``sensor`` or ``number`` component (with ``id`` set to ``player_volume``):
.. code-block:: yaml
on_...:
- http_request.get:
url: https://esphome.io
on_response:
then:
- lambda: |-
json::parse_json(id(http_request_data).get_string(), [](JsonObject root) {
id(player_volume).publish_state(root["vol"]);
});
**Note:** don't forget to set the ``id`` for the main ``http_request`` component, to ``http_request_data``.
See Also
--------