From 7bfbc6f228b2ed676aea22d43489acda681da50b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?H=2E=20=C3=81rkosi=20R=C3=B3bert?= Date: Sat, 12 Mar 2022 19:27:48 +0100 Subject: [PATCH] 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 --- components/http_request.rst | 31 +++++++++++++++++++++++++++---- 1 file changed, 27 insertions(+), 4 deletions(-) diff --git a/components/http_request.rst b/components/http_request.rst index 7dadaf537..791936439 100644 --- a/components/http_request.rst +++ b/components/http_request.rst @@ -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 --------