{"id":42247,"date":"2017-08-29T11:14:22","date_gmt":"2017-08-29T11:14:22","guid":{"rendered":"http:\/\/randomnerdtutorials.com\/?p=42247"},"modified":"2019-04-03T14:05:07","modified_gmt":"2019-04-03T14:05:07","slug":"decoding-and-encoding-json-with-arduino-or-esp8266","status":"publish","type":"post","link":"https:\/\/randomnerdtutorials.com\/decoding-and-encoding-json-with-arduino-or-esp8266\/","title":{"rendered":"Decoding and Encoding JSON with Arduino or ESP8266"},"content":{"rendered":"<p>In this blog post you&#8217;re going to learn how to decode (parse a JSON string) and encode (generate a JSON string) with the ArduinoJson library using the Arduino with the Ethernet shield. This guide also works with the ESP8266 and ESP32 Wi-Fi modules with small changes.<\/p>\n<p><!--more--><\/p>\n<p><img data-recalc-dims=\"1\" fetchpriority=\"high\" decoding=\"async\" class=\"aligncenter wp-image-42498 size-full\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/08\/Arduino-JSON-featured-image.png?resize=1146%2C588&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"\" width=\"1146\" height=\"588\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/08\/Arduino-JSON-featured-image.png?w=1146&amp;quality=100&amp;strip=all&amp;ssl=1 1146w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/08\/Arduino-JSON-featured-image.png?resize=300%2C154&amp;quality=100&amp;strip=all&amp;ssl=1 300w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/08\/Arduino-JSON-featured-image.png?resize=768%2C394&amp;quality=100&amp;strip=all&amp;ssl=1 768w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/08\/Arduino-JSON-featured-image.png?resize=1024%2C525&amp;quality=100&amp;strip=all&amp;ssl=1 1024w\" sizes=\"(max-width: 1146px) 100vw, 1146px\" \/><\/p>\n<p><span style=\"color: #ff0000;\"><strong>Important:<\/strong> this tutorial is only compatible with the ArduinoJSON library 5.13.5.<\/span><\/p>\n<p><img data-recalc-dims=\"1\" decoding=\"async\" class=\"aligncenter size-full wp-image-81910\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/08\/arduino-json-library-installed.png?resize=786%2C179&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"\" width=\"786\" height=\"179\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/08\/arduino-json-library-installed.png?w=786&amp;quality=100&amp;strip=all&amp;ssl=1 786w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/08\/arduino-json-library-installed.png?resize=300%2C68&amp;quality=100&amp;strip=all&amp;ssl=1 300w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/08\/arduino-json-library-installed.png?resize=768%2C175&amp;quality=100&amp;strip=all&amp;ssl=1 768w\" sizes=\"(max-width: 786px) 100vw, 786px\" \/><\/p>\n<h2>What is JSON?<\/h2>\n<p>JSON stands for <strong>J<\/strong>ava<strong>S<\/strong>cript <strong>O<\/strong>bject <strong>N<\/strong>otation. JSON is a lightweight text-based open standard design for exchanging data.<\/p>\n<p>JSON is primarily used for serializing and transmitting structured data over network connection &#8211; transmit data between a server and a client. It is often used in services like APIs (Application Programming Interfaces) and web services that provide public data.<\/p>\n<h2>JSON syntax basics<\/h2>\n<p>In JSON, data is structured in a specific way. JSON uses symbols like <strong>{ } , : &#8221; &#8221; [ ] <\/strong>and it has the following&nbsp;syntax:<\/p>\n<ul>\n<li>Data is represented in key\/value pairs<\/li>\n<li>The colon (:) assigns a value to key<\/li>\n<li>key\/value pairs are separated with commas (,)<\/li>\n<li>Curly brackets hold objects ({ })<\/li>\n<li>Square brackets hold arrays ([ ])<\/li>\n<\/ul>\n<p>For example, to represent data in JSON, the key\/value pairs come as follows:<\/p>\n<pre>{\"<strong>key1<\/strong>\":\"<strong>value1<\/strong>\", \"<strong>key2<\/strong>\":\"<strong>value2<\/strong>\", \"<strong>key3<\/strong>\":\"<strong>value3<\/strong>\"}<\/pre>\n<h2>JSON examples<\/h2>\n<p>In a real world example, you may want structure data about a user:<\/p>\n<pre>{\"<strong>name<\/strong>\":\"<strong>Rui<\/strong>\", \"<strong>country<\/strong>\": \"<strong>Portugal<\/strong>\", \"<strong>age<\/strong>\":<strong>24<\/strong>}<\/pre>\n<p>Or in a IoT project, you may want to structure data from your sensors:<\/p>\n<pre>{\"<strong>temperature<\/strong>\":<strong>27.23<\/strong>, \"<strong>humidity<\/strong>\":<strong>62.05<\/strong>, \"<strong>pressure<\/strong>\":<strong>1013.25<\/strong>}<\/pre>\n<p>In JSON, the values can be another JSON object (sports) or an array (pets) . For example:<\/p>\n<pre>{\n  \"<strong>name<\/strong>\": \"<strong>Rui<\/strong>\",\n  \"<strong>sports<\/strong>\": {\n    \"<strong>outdoor<\/strong>\": \"<strong>hiking<\/strong>\",\n    \"<strong>indoor<\/strong>\": \"<strong>swimming<\/strong>\"\n  },\n  \"<strong>pets<\/strong>\": [\n    \"<strong>Max<\/strong>\",\n    \"<strong>Dique<\/strong>\"\n  ]\n}<\/pre>\n<p>Here we are structuring data about a user and we have several keys: &#8220;<strong>name&#8221;<\/strong>, &#8220;<strong>sports&#8221;<\/strong> and &#8220;<strong>pets&#8221;.<\/strong><\/p>\n<p>The name has the value Rui assigned. Rui may practice different sports relating to where they are practiced. So, we create another JSON object to save Rui&#8217;s favorite sports. This JSON object is the value of the &#8220;<strong>sports<\/strong>&#8221; key.<\/p>\n<p>The &#8220;<strong>pets&#8221;<\/strong> key has an array that contains Rui&#8217;s pets&#8217; names and it has the values &#8220;<strong>Max<\/strong>&#8221; and &#8220;<strong>Dique<\/strong>&#8221; inside.<\/p>\n<p>Most APIs return data in JSON and most values are JSON objects themselves. The following example shows the data provided by a weather API.<\/p>\n<pre><span id=\"s-1\" class=\"sBrace structure-1\">{&nbsp;<i class=\"fa fa-minus-square-o\"><\/i>&nbsp;<\/span>\n&nbsp;&nbsp;<span id=\"s-2\" class=\"sObjectK\">\"coord\"<\/span><span id=\"s-3\" class=\"sColon\">:<\/span><span id=\"s-4\" class=\"sBrace structure-2\">{&nbsp;<i class=\"fa fa-minus-square-o\"><\/i>&nbsp;<\/span>\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span id=\"s-5\" class=\"sObjectK\">\"lon\"<\/span><span id=\"s-6\" class=\"sColon\">:<\/span><span id=\"s-7\" class=\"sObjectV\">-8.61<\/span><span id=\"s-8\" class=\"sComma\">,<\/span>\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span id=\"s-9\" class=\"sObjectK\">\"lat\"<\/span><span id=\"s-10\" class=\"sColon\">:<\/span><span id=\"s-11\" class=\"sObjectV\">41.15<\/span>\n&nbsp;&nbsp;<span id=\"s-12\" class=\"sBrace structure-2\">}<\/span><span id=\"s-13\" class=\"sComma\">,<\/span>\n&nbsp;&nbsp;<span id=\"s-14\" class=\"sObjectK\">\"weather\"<\/span><span id=\"s-15\" class=\"sColon\">:<\/span><span id=\"s-16\" class=\"sBracket structure-2\">[&nbsp;<i class=\"fa fa-minus-square-o\"><\/i>&nbsp;<\/span>\n&nbsp;&nbsp;&nbsp;&nbsp;<span id=\"s-17\" class=\"sBrace structure-3\">{&nbsp;<i class=\"fa fa-minus-square-o\"><\/i>&nbsp;<\/span>\n&nbsp;&nbsp;    <span id=\"s-18\" class=\"sObjectK\">\"id\"<\/span><span id=\"s-19\" class=\"sColon\">:<\/span><span id=\"s-20\" class=\"sObjectV\">803<\/span><span id=\"s-21\" class=\"sComma\">,<\/span>\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span id=\"s-22\" class=\"sObjectK\">\"main\"<\/span><span id=\"s-23\" class=\"sColon\">:<\/span><span id=\"s-24\" class=\"sObjectV\">\"Clouds\"<\/span><span id=\"s-25\" class=\"sComma\">,<\/span>\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span id=\"s-26\" class=\"sObjectK\">\"description\"<\/span><span id=\"s-27\" class=\"sColon\">:<\/span><span id=\"s-28\" class=\"sObjectV\">\"broken&nbsp;clouds\"<\/span><span id=\"s-29\" class=\"sComma\">,<\/span>\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span id=\"s-30\" class=\"sObjectK\">\"icon\"<\/span><span id=\"s-31\" class=\"sColon\">:<\/span><span id=\"s-32\" class=\"sObjectV\">\"04d\"<\/span>\n&nbsp;&nbsp;&nbsp;&nbsp;<span id=\"s-33\" class=\"sBrace structure-3\">}<\/span>\n&nbsp;&nbsp;<span id=\"s-34\" class=\"sBracket structure-2\">]<\/span><span id=\"s-35\" class=\"sComma\">,\n<\/span><span id=\"s-36\" class=\"sObjectK\">  \"base\"<\/span><span id=\"s-37\" class=\"sColon\">:<\/span><span id=\"s-38\" class=\"sObjectV\">\"stations\"<\/span><span id=\"s-39\" class=\"sComma\">,<\/span>\n&nbsp;&nbsp;<span id=\"s-40\" class=\"sObjectK\">\"main\"<\/span><span id=\"s-41\" class=\"sColon\">:<\/span><span id=\"s-42\" class=\"sBrace structure-2\">{&nbsp;<i class=\"fa fa-minus-square-o\"><\/i>&nbsp;<\/span>\n&nbsp;&nbsp;  <span id=\"s-43\" class=\"sObjectK\">\"temp\"<\/span><span id=\"s-44\" class=\"sColon\">:<\/span><span id=\"s-45\" class=\"sObjectV\">288.15<\/span><span id=\"s-46\" class=\"sComma\">,<\/span>\n&nbsp;&nbsp;&nbsp;&nbsp;<span id=\"s-47\" class=\"sObjectK\">\"pressure\"<\/span><span id=\"s-48\" class=\"sColon\">:<\/span><span id=\"s-49\" class=\"sObjectV\">1020<\/span><span id=\"s-50\" class=\"sComma\">,<\/span>\n&nbsp;&nbsp;&nbsp;&nbsp;<span id=\"s-51\" class=\"sObjectK\">\"humidity\"<\/span><span id=\"s-52\" class=\"sColon\">:<\/span><span id=\"s-53\" class=\"sObjectV\">93<\/span><span id=\"s-54\" class=\"sComma\">,<\/span>\n&nbsp;&nbsp;&nbsp;&nbsp;<span id=\"s-55\" class=\"sObjectK\">\"temp_min\"<\/span><span id=\"s-56\" class=\"sColon\">:<\/span><span id=\"s-57\" class=\"sObjectV\">288.15<\/span><span id=\"s-58\" class=\"sComma\">,<\/span>\n&nbsp;&nbsp;&nbsp;&nbsp;<span id=\"s-59\" class=\"sObjectK\">\"temp_max\"<\/span><span id=\"s-60\" class=\"sColon\">:<\/span><span id=\"s-61\" class=\"sObjectV\">288.15<\/span>\n&nbsp;&nbsp;<span id=\"s-62\" class=\"sBrace structure-2\">}<\/span><span id=\"s-63\" class=\"sComma\">,<\/span>\n  (...)\n<span id=\"s-131\" class=\"sBrace structure-1\">}<\/span><\/pre>\n<p>This API provides a lot of information. For example, the first lines store the coordinates with the longitude and latitude.<span id=\"s-1\" class=\"sBrace structure-1\"><\/span><\/p>\n<h2>Arduino with Ethernet shield<\/h2>\n<p>The examples in this post use an Arduino with an Ethernet shield. Just mount the shield onto your Arduino board and connect it to your network with an RJ45 cable to establish an Internet connection (as shown in the figure below).<\/p>\n<p><img decoding=\"async\" class=\"aligncenter\" src=\"https:\/\/i1.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/03\/Ethernet-Shield.jpg?resize=700%2C478&amp;ssl=1\" sizes=\"(max-width: 700px) 100vw, 700px\" srcset=\"https:\/\/i1.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/03\/Ethernet-Shield.jpg?w=700&amp;ssl=1 700w, https:\/\/i1.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/03\/Ethernet-Shield.jpg?resize=150%2C102&amp;ssl=1 150w, https:\/\/i1.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/03\/Ethernet-Shield.jpg?resize=300%2C205&amp;ssl=1 300w, https:\/\/i1.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/03\/Ethernet-Shield.jpg?resize=80%2C55&amp;ssl=1 80w, https:\/\/i1.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/03\/Ethernet-Shield.jpg?resize=220%2C150&amp;ssl=1 220w, https:\/\/i1.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/03\/Ethernet-Shield.jpg?resize=146%2C100&amp;ssl=1 146w, https:\/\/i1.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/03\/Ethernet-Shield.jpg?resize=349%2C238&amp;ssl=1 349w, https:\/\/i1.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/03\/Ethernet-Shield.jpg?resize=608%2C415&amp;ssl=1 608w\" alt=\"\" width=\"700\" height=\"478\"><\/p>\n<p><strong>Note:<\/strong> the examples provided in this tutorial also work with the ESP8266 and ESP32 with small changes.<\/p>\n<h2>Preparing the Arduino IDE<\/h2>\n<p>The easiest way to&nbsp;decode and encode JSON strings with the Arduino IDE is using the ArduinoJson library 5.13.5 which was designed to be the most intuitive JSON library, with the smallest footprint and most efficiently memory management for Arduino.<\/p>\n<p>It has been written with Arduino in mind, but it isn&#8217;t linked to Arduino libraries so you can use this library in any other C++ project. There&#8217;s also a <a href=\"https:\/\/arduinojson.org\/\" target=\"_blank\" rel=\"noopener nofollow noreferrer\">documentation<\/a> website for the library with examples and with the API reference.<\/p>\n<h3>Features<\/h3>\n<ul>\n<li>JSON decoding (comments are supported)<\/li>\n<li>JSON encoding (with optional indentation)<\/li>\n<li>Elegant API, very easy to use<\/li>\n<li>Fixed memory allocation (zero malloc)<\/li>\n<li>No data duplication (zero copy)<\/li>\n<li>Portable (written in C++98)<\/li>\n<li>Self-contained (no external dependency)<\/li>\n<li>Small footprint<\/li>\n<li>Header-only library<\/li>\n<li>MIT License<\/li>\n<\/ul>\n<h3>Compatible with<\/h3>\n<ul>\n<li>Arduino boards: Uno, Due, Mini, Micro, Yun&#8230;<\/li>\n<li>ESP8266, ESP32 and&nbsp;WeMos boards<\/li>\n<li>Teensy, RedBearLab boards, Intel Edison and Galileo<\/li>\n<li>PlatformIO, Particle and Energia<\/li>\n<\/ul>\n<h3>Installing the ArduinoJson library<\/h3>\n<p>For this project you need to install the ArduinoJson library in your Arduino IDE:<\/p>\n<ol>\n<li><a href=\"https:\/\/github.com\/bblanchon\/ArduinoJson\/archive\/v5.13.5.zip\" target=\"_blank\" rel=\"noopener noreferrer\">Click here to download the ArduinoJson version 5.13.5<\/a>. You should have a .zip folder in your Downloads folder<\/li>\n<li>Unzip the .zip folder and you should get ArduinoJson-master folder<\/li>\n<li>Rename your folder from&nbsp;<del>ArduinoJson-master<\/del> to&nbsp;<strong>ArduinoJson<\/strong><\/li>\n<li>Move the ArduinoJson folder to your Arduino IDE installation libraries folder<\/li>\n<li>Finally, re-open your Arduino IDE<\/li>\n<\/ol>\n<h2>Decoding JSON &#8211; Parse JSON string<\/h2>\n<p>Let&#8217;s start by decoding\/parsing the next JSON string:<\/p>\n<pre>{\"sensor\":\"gps\",\"time\":1351824120,\"data\":[48.756080,2.302038]}<\/pre>\n<p>Import the ArduinoJson library:<\/p>\n<pre><a id=\"user-content-decoding--parsing\" class=\"anchor\" href=\"https:\/\/github.com\/bblanchon\/ArduinoJson#decoding--parsing\" aria-hidden=\"true\"><\/a><strong>#include &lt;ArduinoJson.h&gt;<\/strong><\/pre>\n<p>Arduino JSON uses a preallocated memory pool to store the JsonObject tree, this is done by the StaticJsonBuffer. You can use <a href=\"https:\/\/arduinojson.org\/v5\/assistant\/\" target=\"_blank\" rel=\"noopener nofollow noreferrer\">ArduinoJson Assistant<\/a>&nbsp;to compute the exact buffer size, but for this example 200 is enough.<\/p>\n<pre><strong>StaticJsonBuffer&lt;200&gt; jsonBuffer;<\/strong><\/pre>\n<p>Create a char array called<strong> json[]<\/strong> to store a sample JSON string:<\/p>\n<pre><strong>char json[] = \"{\\\"sensor\\\":\\\"gps\\\",\\\"time\\\":1351824120,\\\"data\\\":[48.756080,2.302038]}\"; <\/strong><\/pre>\n<p>Use the function <strong>parseObject()<\/strong> to decode\/parse the JSON string to a JsonObject called <strong>root<\/strong>.<\/p>\n<pre><strong>JsonObject&amp; root = jsonBuffer.parseObject(json);<\/strong><\/pre>\n<p>To check if the decoding\/parsing was successful, you can call <strong>root.success()<\/strong>:<\/p>\n<pre><strong>if(!root.success())<\/strong> {\n  Serial.println(\"parseObject() failed\");\n  return <strong>false<\/strong>;\n}<\/pre>\n<p>The result can be false for three reasons:<\/p>\n<ul>\n<li>the JSON string has invalid syntax;<\/li>\n<li>the JSON string doesn\u2019t represent an object;<\/li>\n<li>the StaticJsonBuffer is too small &#8211; use&nbsp;<a href=\"https:\/\/arduinojson.org\/v5\/assistant\/\" target=\"_blank\" rel=\"noopener nofollow noreferrer\">ArduinoJson Assistant<\/a>&nbsp;to compute the buffer size.<\/li>\n<\/ul>\n<p>Now that the object or array is in memory, you can extract the data easily. The simplest way is to use the JsonObject <strong>root<\/strong>:<\/p>\n<pre>const char* <strong>sensor<\/strong> = root[\"sensor\"];\nlong <strong>time<\/strong> = root[\"time\"];\ndouble <strong>latitude<\/strong> = root[\"data\"][0];\ndouble <strong>longitude<\/strong> = root[\"data\"][1];<\/pre>\n<p>You can use the decoded variables sensor, time, latitude or longitude in your code logic.<\/p>\n<h3>OpenWeatherMap API<\/h3>\n<p>For a real example using an Arduino with an Ethernet shield, we&#8217;re going to use a free API from <a href=\"https:\/\/openweathermap.org\" target=\"_blank\" rel=\"noopener noreferrer\">OpenWeatherMap<\/a>&nbsp;to request the day\u2019s weather forecast for your chosen location.<\/p>\n<p>Learning to use APIs is a great skill because it allows you access to a wide variety of constantly-changing information, such as the current stock price, the currency exchange rate, the latest news, traffic updates, and much more.<\/p>\n<p><strong>Using the API<\/strong><\/p>\n<p>OpenWeatherMap\u2019s free plan provides everything you need for thins example. To use the API you need an API key, known as the APIID. To get an APIID:<\/p>\n<ol>\n<li>Open a browser and go to <a href=\"https:\/\/openweathermap.org\" target=\"_blank\" rel=\"noopener noreferrer\">OpenWeatherMap<\/a><\/li>\n<li>Press the <strong>Sign up<\/strong> button and create a free account<\/li>\n<li>Once your account is created, you\u2019ll be presented with a dashboard that contains several tabs (see figure below)<\/li>\n<li>Select the <strong>API Keys<\/strong> tab and copy your unique <strong>Key<\/strong><\/li>\n<\/ol>\n<p><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-42468\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/08\/openWeatherMap-api-key.png?resize=998%2C474&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"\" width=\"998\" height=\"474\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/08\/openWeatherMap-api-key.png?w=998&amp;quality=100&amp;strip=all&amp;ssl=1 998w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/08\/openWeatherMap-api-key.png?resize=300%2C142&amp;quality=100&amp;strip=all&amp;ssl=1 300w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/08\/openWeatherMap-api-key.png?resize=768%2C365&amp;quality=100&amp;strip=all&amp;ssl=1 768w\" sizes=\"(max-width: 998px) 100vw, 998px\" \/><\/p>\n<p>This is a unique key you need to pull information from the site. Copy and paste this key somewhere, you\u2019ll need it in a moment.<\/p>\n<p>To pull information on weather in your chosen location, enter the following URL with the sections in curly brackets replaced with your chosen location information and your unique API key:<\/p>\n<pre>http:\/\/api.openweathermap.org\/data\/2.5\/weather?q=<span style=\"color: #ff0000;\"><strong>{your city}<\/strong><\/span>,<span style=\"color: #ff0000;\"><strong>{your country code}<\/strong><\/span>&amp;APPID=<strong><span style=\"color: #ff0000;\">{your API Key}<\/span><\/strong><\/pre>\n<p>Replace <span style=\"color: #ff0000;\"><strong>{your city}<\/strong><\/span> with the city you want data for, <span style=\"color: #ff0000;\"><strong>{your country code}<\/strong><\/span> with the country code for that city, and <span style=\"color: #ff0000;\"><strong>{your API key}<\/strong><\/span> with your unique API key we found previously. For example, our API URL for the town of Porto in Portugal, after replacing with the details, would be:<\/p>\n<pre>http:\/\/api.openweathermap.org\/data\/2.5\/weather?q=Porto,PT&amp;APPID=801d2603e9f2e1c70e042e4------<\/pre>\n<p><strong>Note<\/strong>: more information on using the API to get weather information is available <a href=\"https:\/\/openweathermap.org\/current\" target=\"_blank\" rel=\"noopener noreferrer\">here<\/a>.<\/p>\n<p>Copy your URL into your browser and it should give you a bunch of information that corresponds to your local weather information.<\/p>\n<p><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-42471\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/08\/open-weather-map-test-api.png?resize=841%2C319&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"\" width=\"841\" height=\"319\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/08\/open-weather-map-test-api.png?w=841&amp;quality=100&amp;strip=all&amp;ssl=1 841w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/08\/open-weather-map-test-api.png?resize=300%2C114&amp;quality=100&amp;strip=all&amp;ssl=1 300w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/08\/open-weather-map-test-api.png?resize=768%2C291&amp;quality=100&amp;strip=all&amp;ssl=1 768w\" sizes=\"(max-width: 841px) 100vw, 841px\" \/><\/p>\n<p>In our case, it returns the weather in Porto, Portugal on the day of writing:<\/p>\n<pre>{\n  \"coord\": {\n    \"lon\": -8.61,\n    \"lat\": 41.15\n  },\n  \"weather\": [\n    {\n      \"id\": 701,\n      \"main\": \"Mist\",\n      \"description\": \"mist\",\n      \"icon\": \"50d\"\n    }\n  ],\n  \"base\": \"stations\",\n  \"main\": {\n    \"temp\": 290.86,\n    \"pressure\": 1014,\n    \"humidity\": 88,\n    \"temp_min\": 290.15,\n    \"temp_max\": 292.15\n  },\n  (...)\n}<\/pre>\n<h3>Making an API Request with Arduino<\/h3>\n<p>Now that you have a URL that returns your local weather data. You can automate this task and access that data in your Arduino or ESP8266 projects. Here&#8217;s the full script that you need to upload to your Arduino with Ethernet shield to return the temperature in Kelvin and humidity:<\/p>\n<pre style=\"max-height: 40em; margin-bottom: 20px;\"><code class=\"language-c\">\/*\n * Rui Santos \n * Complete Project Details http:\/\/randomnerdtutorials.com\n * Based on the Arduino Ethernet Web Client Example\n * and on the sketch &quot;Sample Arduino Json Web Client&quot; of the Arduino JSON library by Benoit Blanchon (bblanchon.github.io\/ArduinoJson)\n *\/\n\n#include &lt;ArduinoJson.h&gt;\n#include &lt;Ethernet.h&gt;\n#include &lt;SPI.h&gt;\n\nEthernetClient client;\n\n\/\/ Name address for Open Weather Map API\nconst char* server = &quot;api.openweathermap.org&quot;;\n\n\/\/ Replace with your unique URL resource\nconst char* resource = &quot;REPLACE_WITH_YOUR_URL_RESOURCE&quot;;\n\n\/\/ How your resource variable should look like, but with your own COUNTRY CODE, CITY and API KEY (that API KEY below is just an example):\n\/\/const char* resource = &quot;\/data\/2.5\/weather?q=Porto,pt&amp;appid=bd939aa3d23ff33d3c8f5dd1&quot;;\n\nconst unsigned long HTTP_TIMEOUT = 10000;  \/\/ max respone time from server\nconst size_t MAX_CONTENT_SIZE = 512;       \/\/ max size of the HTTP response\n\nbyte mac[] = {0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED};\n\n\/\/ The type of data that we want to extract from the page\nstruct clientData {\n  char temp[8];\n  char humidity[8];\n};\n\n\/\/ ARDUINO entry point #1: runs once when you press reset or power the board\nvoid setup() {\n  Serial.begin(9600);\n  while (!Serial) {\n    ;  \/\/ wait for serial port to initialize\n  }\n  Serial.println(&quot;Serial ready&quot;);\n  if(!Ethernet.begin(mac)) {\n    Serial.println(&quot;Failed to configure Ethernet&quot;);\n    return;\n  }\n  Serial.println(&quot;Ethernet ready&quot;);\n  delay(1000);\n}\n\n\/\/ ARDUINO entry point #2: runs over and over again forever\nvoid loop() {\n  if(connect(server)) {\n    if(sendRequest(server, resource) &amp;&amp; skipResponseHeaders()) {\n      clientData clientData;\n      if(readReponseContent(&amp;clientData)) {\n        printclientData(&amp;clientData);\n      }\n    }\n  }\n  disconnect();\n  wait();\n}\n\n\/\/ Open connection to the HTTP server\nbool connect(const char* hostName) {\n  Serial.print(&quot;Connect to &quot;);\n  Serial.println(hostName);\n\n  bool ok = client.connect(hostName, 80);\n\n  Serial.println(ok ? &quot;Connected&quot; : &quot;Connection Failed!&quot;);\n  return ok;\n}\n\n\/\/ Send the HTTP GET request to the server\nbool sendRequest(const char* host, const char* resource) {\n  Serial.print(&quot;GET &quot;);\n  Serial.println(resource);\n\n  client.print(&quot;GET &quot;);\n  client.print(resource);\n  client.println(&quot; HTTP\/1.1&quot;);\n  client.print(&quot;Host: &quot;);\n  client.println(host);\n  client.println(&quot;Connection: close&quot;);\n  client.println();\n\n  return true;\n}\n\n\/\/ Skip HTTP headers so that we are at the beginning of the response's body\nbool skipResponseHeaders() {\n  \/\/ HTTP headers end with an empty line\n  char endOfHeaders[] = &quot;\\r\\n\\r\\n&quot;;\n\n  client.setTimeout(HTTP_TIMEOUT);\n  bool ok = client.find(endOfHeaders);\n\n  if (!ok) {\n    Serial.println(&quot;No response or invalid response!&quot;);\n  }\n  return ok;\n}\n\n\/\/ Parse the JSON from the input string and extract the interesting values\n\/\/ Here is the JSON we need to parse\n\/*{\n    &quot;coord&quot;: {\n        &quot;lon&quot;: -8.61,\n        &quot;lat&quot;: 41.15\n    },\n    &quot;weather&quot;: [\n        {\n            &quot;id&quot;: 800,\n            &quot;main&quot;: &quot;Clear&quot;,\n            &quot;description&quot;: &quot;clear sky&quot;,\n            &quot;icon&quot;: &quot;01d&quot;\n        }\n    ],\n    &quot;base&quot;: &quot;stations&quot;,\n    &quot;main&quot;: {\n        &quot;temp&quot;: 296.15,\n        &quot;pressure&quot;: 1020,\n        &quot;humidity&quot;: 69,\n        &quot;temp_min&quot;: 296.15,\n        &quot;temp_max&quot;: 296.15\n    },\n    &quot;visibility&quot;: 10000,\n    &quot;wind&quot;: {\n        &quot;speed&quot;: 4.6,\n        &quot;deg&quot;: 320\n    },\n    &quot;clouds&quot;: {\n        &quot;all&quot;: 0\n    },\n    &quot;dt&quot;: 1499869800,\n    &quot;sys&quot;: {\n        &quot;type&quot;: 1,\n        &quot;id&quot;: 5959,\n        &quot;message&quot;: 0.0022,\n        &quot;country&quot;: &quot;PT&quot;,\n        &quot;sunrise&quot;: 1499836380,\n        &quot;sunset&quot;: 1499890019\n    },\n    &quot;id&quot;: 2735943,\n    &quot;name&quot;: &quot;Porto&quot;,\n    &quot;cod&quot;: 200\n}*\/\n\nbool readReponseContent(struct clientData* clientData) {\n  \/\/ Compute optimal size of the JSON buffer according to what we need to parse.\n  \/\/ See https:\/\/bblanchon.github.io\/ArduinoJson\/assistant\/\n  const size_t bufferSize = JSON_ARRAY_SIZE(1) + JSON_OBJECT_SIZE(1) + \n      2*JSON_OBJECT_SIZE(2) + JSON_OBJECT_SIZE(4) + JSON_OBJECT_SIZE(5) + \n      JSON_OBJECT_SIZE(6) + JSON_OBJECT_SIZE(12) + 390;\n  DynamicJsonBuffer jsonBuffer(bufferSize);\n\n  JsonObject&amp; root = jsonBuffer.parseObject(client);\n\n  if (!root.success()) {\n    Serial.println(&quot;JSON parsing failed!&quot;);\n    return false;\n  }\n\n  \/\/ Here were copy the strings we're interested in using to your struct data\n  strcpy(clientData-&gt;temp, root[&quot;main&quot;][&quot;temp&quot;]);\n  strcpy(clientData-&gt;humidity, root[&quot;main&quot;][&quot;humidity&quot;]);\n  \/\/ It's not mandatory to make a copy, you could just use the pointers\n  \/\/ Since, they are pointing inside the &quot;content&quot; buffer, so you need to make\n  \/\/ sure it's still in memory when you read the string\n\n  return true;\n}\n\n\/\/ Print the data extracted from the JSON\nvoid printclientData(const struct clientData* clientData) {\n  Serial.print(&quot;Temp = &quot;);\n  Serial.println(clientData-&gt;temp);\n  Serial.print(&quot;Humidity = &quot;);\n  Serial.println(clientData-&gt;humidity);\n}\n\n\/\/ Close the connection with the HTTP server\nvoid disconnect() {\n  Serial.println(&quot;Disconnect&quot;);\n  client.stop();\n}\n\n\/\/ Pause for a 1 minute\nvoid wait() {\n  Serial.println(&quot;Wait 60 seconds&quot;);\n  delay(60000);\n}\n<\/code><\/pre>\n\t<p style=\"text-align:center\"><a class=\"rntwhite\" href=\"https:\/\/github.com\/RuiSantosdotme\/Random-Nerd-Tutorials\/raw\/master\/Projects\/Arduino-JSON\/Arduino_HTTP_GET_Client.ino\" target=\"_blank\">View raw code<\/a><\/p>\n<p><strong>Note:<\/strong> make sure your replace the resource variable with your unique OpenWeatherMap URL resource:<\/p>\n<pre>const char* resource = \"<strong><span style=\"color: #ff0000;\">REPLACE_WITH_YOUR_URL_RESOURCE<\/span><\/strong>\";<\/pre>\n<h4>Modifying the code for your project<\/h4>\n<p>In this example, the Arduino performs an HTTP GET request to a desired service (in this case the OpenWeatherMap API), but you could change it to request any other web service. We won&#8217;t explain the Arduino code line by line.<\/p>\n<p>For this project it&#8217;s important that you understand what you need to change in the Arduino code to decode\/parse any JSON response. Follow these next three steps.<\/p>\n<h4>STEP #1 &#8211; struct<\/h4>\n<p>Create a data structure that can store the information that you&#8217;ll want to extract from the API. In this case, we want to store the temperature and humidity in char arrays:<\/p>\n<pre><strong>struct clientData {<\/strong>\n<strong>  char temp[8];<\/strong>\n<strong>  char humidity[8];<\/strong>\n<strong>};<\/strong><\/pre>\n<h4>STEP #2 &#8211; JsonBuffer size<\/h4>\n<p>Go to the <a href=\"https:\/\/arduinojson.org\/v5\/assistant\/\" target=\"_blank\" rel=\"noopener nofollow noreferrer\">ArduinoJson Assistant<\/a>&nbsp;and copy the full OpenWeatherMap API response to the Input field.<\/p>\n<p><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" class=\"aligncenter wp-image-42489\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/08\/ArduinoJson-Assistant-example.png?resize=740%2C379&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"\" width=\"740\" height=\"379\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/08\/ArduinoJson-Assistant-example.png?w=1005&amp;quality=100&amp;strip=all&amp;ssl=1 1005w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/08\/ArduinoJson-Assistant-example.png?resize=300%2C154&amp;quality=100&amp;strip=all&amp;ssl=1 300w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/08\/ArduinoJson-Assistant-example.png?resize=768%2C394&amp;quality=100&amp;strip=all&amp;ssl=1 768w\" sizes=\"(max-width: 740px) 100vw, 740px\" \/><\/p>\n<p>Copy the <strong>Expression<\/strong> generated (see the preceding figure), in my case:<\/p>\n<pre><strong>JSON_ARRAY_SIZE(1) + JSON_OBJECT_SIZE(1) + 2*JSON_OBJECT_SIZE(2) + JSON_OBJECT_SIZE(4) + JSON_OBJECT_SIZE(5) + JSON_OBJECT_SIZE(6) + JSON_OBJECT_SIZE(12)<\/strong><\/pre>\n<p>You&#8217;ll need to edit the <strong>readReponseContent()<\/strong> function with your the generated&nbsp;<strong>JsonBuffer<\/strong> size from&nbsp;ArduinoJson Assistant to allocate the appropriate memory for decoding the JSON response from an API:<\/p>\n<pre>bool <strong>readReponseContent<\/strong>(struct clientData* clientData) {\n  const size_t bufferSize = <span style=\"color: #ff0000;\"><strong>JSON_ARRAY_SIZE(1) + JSON_OBJECT_SIZE(1) + <\/strong>\n<strong>    2*JSON_OBJECT_SIZE(2) + JSON_OBJECT_SIZE(4) + JSON_OBJECT_SIZE(5) + <\/strong>\n<strong>    JSON_OBJECT_SIZE(6) + JSON_OBJECT_SIZE(12) + 390;&nbsp;\n\n<\/strong><\/span>  DynamicJsonBuffer jsonBuffer(bufferSize);\n  JsonObject&amp; root = jsonBuffer.parseObject(client);<\/pre>\n<p>&nbsp;<\/p>\n<p>Still inside the&nbsp;<strong>readReponseContent()<\/strong> function you need to copy the variables that you need for your project to your struct data:<\/p>\n<pre>strcpy(<strong>clientData-&gt;temp, root[\"main\"][\"temp\"]<\/strong>);\nstrcpy(<strong>clientData-&gt;humidity, root[\"main\"][\"humidity\"]<\/strong>);<\/pre>\n<h4>STEP #3 &#8211; accessing the decoded data<\/h4>\n<p>Then, you can easily access the decoded JSON data in your Arduino code and do something with it. In this example we&#8217;re simply printing the temperature in Kelvin and humidity in the Arduino IDE serial monitor:<\/p>\n<pre>void <strong>printclientData<\/strong>(const struct clientData* clientData) {\n  Serial.print(\"Temp = \");\n  Serial.println(<strong>clientData-&gt;temp<\/strong>);\n  Serial.print(\"Humidity = \");\n  Serial.println(<strong>clientData-&gt;humidity<\/strong>);\n}<\/pre>\n<h3>Demonstration<\/h3>\n<p>Open the Arduino IDE serial monitor at a baud rate of 9600 and you&#8217;ll see the temperature in Kelvin and the humidity in percentage being printed in the Serial monitor every 60 seconds.<\/p>\n<p><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-42472\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/08\/arduino-ide-serial-monitor-open-weather-map.png?resize=696%2C438&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"\" width=\"696\" height=\"438\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/08\/arduino-ide-serial-monitor-open-weather-map.png?w=696&amp;quality=100&amp;strip=all&amp;ssl=1 696w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/08\/arduino-ide-serial-monitor-open-weather-map.png?resize=300%2C189&amp;quality=100&amp;strip=all&amp;ssl=1 300w\" sizes=\"(max-width: 696px) 100vw, 696px\" \/><\/p>\n<p>You can access the rest of the information in the OpenWeatherMap API response, but for demonstration purposes we only decoded the temperature and humidity.<\/p>\n<h2>Encoding JSON &#8211; Generate JSON string<\/h2>\n<p>Let&#8217;s learn how to encode\/generate the next JSON string:<\/p>\n<pre>{\"sensor\":\"gps\",\"time\":1351824120,\"data\":[48.756080,2.302038]}<\/pre>\n<p>You can read the docs about enconding&nbsp;<a href=\"http:\/\/arduinojson.org\/doc\/encoding\/\" target=\"_blank\" rel=\"noopener nofollow noreferrer\">here<\/a>.<\/p>\n<p>Import the ArduinoJson library:<\/p>\n<pre><a id=\"user-content-decoding--parsing\" class=\"anchor\" href=\"https:\/\/github.com\/bblanchon\/ArduinoJson#decoding--parsing\" aria-hidden=\"true\"><\/a><strong>#include &lt;ArduinoJson.h&gt;<\/strong><\/pre>\n<p>Arduino JSON uses a preallocated memory pool to store the object tree, this is done by the StaticJsonBuffer. You can use <a href=\"https:\/\/arduinojson.org\/v5\/assistant\/\" target=\"_blank\" rel=\"noopener nofollow noreferrer\">ArduinoJson Assistant<\/a>&nbsp;to compute the exact buffer size, but for this example 200 is enough.<\/p>\n<pre><strong>StaticJsonBuffer&lt;200&gt; jsonBuffer;<\/strong><\/pre>\n<p>Create a JsonObject called root that will hold your data. Then, assign the values gps and 1351824120 to the <strong>sensor<\/strong> and <strong>time<\/strong> keys, respectively:<\/p>\n<pre>JsonObject&amp; <strong>root<\/strong> = jsonBuffer.createObject();\nroot[\"<strong>sensor<\/strong>\"] = \"gps\";\nroot[\"<strong>time<\/strong>\"] = 1351824120;\n<\/pre>\n<p>Then, to hold an array inside a <strong>data<\/strong> key, you do the following:<\/p>\n<pre>JsonArray&amp; data = root.createNestedArray(\"<strong>data<\/strong>\");\n<strong>data.add(48.756080);\ndata.add(2.302038);<\/strong><\/pre>\n<p>It is very likely that you&#8217;ll need to print the generated JSON in your Serial monitor for debugging purposes, to do that:<\/p>\n<pre><strong>root.printTo(Serial);<\/strong><\/pre>\n<p>After having your information encoded in a JSON string you could post it to another device or web service as shown in the next example.<\/p>\n<h2>Encoding example with Arduino and Node-RED<\/h2>\n<p>For this example you need to Node-RED or a similar software that can receive HTTP POST requests. You can install Node-RED on your computer, but I recommend&nbsp;<a href=\"https:\/\/randomnerdtutorials.com\/getting-started-with-node-red-on-raspberry-pi\/\">running Node-RED on a Raspberry Pi<\/a>.<\/p>\n<h3>Creating the flow<\/h3>\n<p>In this flow, you\u2019re going to receive an HTTP POST request and print the receive data in the <strong>Debug<\/strong> window. Follow these next 6 steps to create your flow:<\/p>\n<p><strong>1)<\/strong> Open the Node-RED software in your browser<\/p>\n<p><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-42480\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/08\/node-red-software-access.png?resize=397%2C183&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"\" width=\"397\" height=\"183\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/08\/node-red-software-access.png?w=397&amp;quality=100&amp;strip=all&amp;ssl=1 397w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/08\/node-red-software-access.png?resize=300%2C138&amp;quality=100&amp;strip=all&amp;ssl=1 300w\" sizes=\"(max-width: 397px) 100vw, 397px\" \/><\/p>\n<p><strong>2)<\/strong> Drag an <strong>HTTP input<\/strong> node and a <strong>debug<\/strong> node<\/p>\n<p><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-42479\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/08\/1_Node-RED_Flow_JSON_POST.png?resize=324%2C45&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"\" width=\"324\" height=\"45\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/08\/1_Node-RED_Flow_JSON_POST.png?w=324&amp;quality=100&amp;strip=all&amp;ssl=1 324w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/08\/1_Node-RED_Flow_JSON_POST.png?resize=300%2C42&amp;quality=100&amp;strip=all&amp;ssl=1 300w\" sizes=\"(max-width: 324px) 100vw, 324px\" \/><\/p>\n<p><strong>3)<\/strong> Edit the&nbsp;<strong>HTTP input<\/strong>&nbsp;by adding the <strong>POST<\/strong> method and the <strong>\/json-post-example<\/strong> URL<\/p>\n<p><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-42475\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/08\/2_Node-RED_Flow_JSON_POST.png?resize=511%2C257&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"\" width=\"511\" height=\"257\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/08\/2_Node-RED_Flow_JSON_POST.png?w=511&amp;quality=100&amp;strip=all&amp;ssl=1 511w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/08\/2_Node-RED_Flow_JSON_POST.png?resize=300%2C151&amp;quality=100&amp;strip=all&amp;ssl=1 300w\" sizes=\"(max-width: 511px) 100vw, 511px\" \/><\/p>\n<p><strong>4<\/strong>) You can leave the default settings for the&nbsp;<strong>debug&nbsp;<\/strong>node<\/p>\n<p><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-42476\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/08\/3_Node-RED_Flow_JSON_POST.png?resize=504%2C239&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"\" width=\"504\" height=\"239\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/08\/3_Node-RED_Flow_JSON_POST.png?w=504&amp;quality=100&amp;strip=all&amp;ssl=1 504w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/08\/3_Node-RED_Flow_JSON_POST.png?resize=300%2C142&amp;quality=100&amp;strip=all&amp;ssl=1 300w\" sizes=\"(max-width: 504px) 100vw, 504px\" \/><\/p>\n<p><strong>5)<\/strong> Connect your nodes<\/p>\n<p><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-42477\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/08\/4_Node-RED_Flow_JSON_POST.png?resize=444%2C43&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"\" width=\"444\" height=\"43\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/08\/4_Node-RED_Flow_JSON_POST.png?w=444&amp;quality=100&amp;strip=all&amp;ssl=1 444w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/08\/4_Node-RED_Flow_JSON_POST.png?resize=300%2C29&amp;quality=100&amp;strip=all&amp;ssl=1 300w\" sizes=\"(max-width: 444px) 100vw, 444px\" \/><\/p>\n<p><strong>6)<\/strong> To save your application, you need to click the deploy button on the top right corner<\/p>\n<p><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-40013\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/06\/11_deploy_button.png?resize=138%2C40&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"\" width=\"138\" height=\"40\"><\/p>\n<p>Your application is saved and ready.<\/p>\n<h3>Send JSON data with Arduino<\/h3>\n<p>After having Node-RED prepared to receive POST requests at the \/json-post-example URL, you can use the next code example on an Arduino with an Ethernet shield to send data to it.<\/p>\n<pre style=\"max-height: 40em; margin-bottom: 20px;\"><code class=\"language-c\">\/*\n * Rui Santos \n * Complete Project Details http:\/\/randomnerdtutorials.com\n * Based on the Arduino Ethernet Web Client Example\n * and on the sketch &quot;Sample Arduino Json Web Client&quot; of the Arduino JSON library by Benoit Blanchon (bblanchon.github.io\/ArduinoJson)\n *\/\n\n#include &lt;ArduinoJson.h&gt;\n#include &lt;Ethernet.h&gt;\n#include &lt;SPI.h&gt;\n\nEthernetClient client;\n\n\/\/ Replace with your Raspberry Pi IP address\nconst char* server = &quot;REPLACE_WITH_YOUR_RASPBERRY_PI_IP_ADDRESS&quot;;\n\n\/\/ Replace with your server port number frequently port 80 - with Node-RED you need to use port 1880\nint portNumber = 1880;\n\n\/\/ Replace with your unique URL resource\nconst char* resource = &quot;\/json-post-example&quot;;\n\nconst unsigned long HTTP_TIMEOUT = 10000;  \/\/ max respone time from server\nconst size_t MAX_CONTENT_SIZE = 512;       \/\/ max size of the HTTP response\n\nbyte mac[] = {0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED};\n\n\/\/ ARDUINO entry point #1: runs once when you press reset or power the board\nvoid setup() {\n  Serial.begin(9600);\n  while(!Serial) {\n    ;  \/\/ wait for serial port to initialize\n  }\n  Serial.println(&quot;Serial ready&quot;);\n  if(!Ethernet.begin(mac)) {\n    Serial.println(&quot;Failed to configure Ethernet&quot;);\n    return;\n  }\n  Serial.println(&quot;Ethernet ready&quot;);\n  delay(1000);\n}\n\n\/\/ ARDUINO entry point #2: runs over and over again forever\nvoid loop() {\n  if(connect(server, portNumber)) {\n    if(sendRequest(server, resource) &amp;&amp; skipResponseHeaders()) {\n      Serial.print(&quot;HTTP POST request finished.&quot;);\n    }\n  }\n  disconnect();\n  wait();\n}\n\n\/\/ Open connection to the HTTP server (Node-RED running on Raspberry Pi)\nbool connect(const char* hostName, int portNumber) {\n  Serial.print(&quot;Connect to &quot;);\n  Serial.println(hostName);\n\n  bool ok = client.connect(hostName, portNumber);\n\n  Serial.println(ok ? &quot;Connected&quot; : &quot;Connection Failed!&quot;);\n  return ok;\n}\n\n\/\/ Send the HTTP POST request to the server\nbool sendRequest(const char* host, const char* resource) {\n  \/\/ Reserve memory space for your JSON data\n  StaticJsonBuffer&lt;200&gt; jsonBuffer;\n  \n  \/\/ Build your own object tree in memory to store the data you want to send in the request\n  JsonObject&amp; root = jsonBuffer.createObject();\n  root[&quot;sensor&quot;] = &quot;dht11&quot;;\n  \n  JsonObject&amp; data = root.createNestedObject(&quot;data&quot;);\n  data.set(&quot;temperature&quot;, &quot;30.1&quot;);\n  data.set(&quot;humidity&quot;, &quot;70.1&quot;);\n  \n  \/\/ Generate the JSON string\n  root.printTo(Serial);\n  \n  Serial.print(&quot;POST &quot;);\n  Serial.println(resource);\n\n  client.print(&quot;POST &quot;);\n  client.print(resource);\n  client.println(&quot; HTTP\/1.1&quot;);\n  client.print(&quot;Host: &quot;);\n  client.println(host);\n  client.println(&quot;Connection: close\\r\\nContent-Type: application\/json&quot;);\n  client.print(&quot;Content-Length: &quot;);\n  client.print(root.measureLength());\n  client.print(&quot;\\r\\n&quot;);\n  client.println();\n  root.printTo(client);\n\n  return true;\n}\n\n\/\/ Skip HTTP headers so that we are at the beginning of the response's body\nbool skipResponseHeaders() {\n  \/\/ HTTP headers end with an empty line\n  char endOfHeaders[] = &quot;\\r\\n\\r\\n&quot;;\n\n  client.setTimeout(HTTP_TIMEOUT);\n  bool ok = client.find(endOfHeaders);\n\n  if(!ok) {\n    Serial.println(&quot;No response or invalid response!&quot;);\n  }\n  return ok;\n}\n\n\/\/ Close the connection with the HTTP server\nvoid disconnect() {\n  Serial.println(&quot;Disconnect&quot;);\n  client.stop();\n}\n\n\/\/ Pause for a 1 minute\nvoid wait() {\n  Serial.println(&quot;Wait 60 seconds&quot;);\n  delay(60000);\n}\n<\/code><\/pre>\n\t<p style=\"text-align:center\"><a class=\"rntwhite\" href=\"https:\/\/github.com\/RuiSantosdotme\/Random-Nerd-Tutorials\/raw\/master\/Projects\/Arduino-JSON\/Arduino_HTTP_POST_Client.ino\" target=\"_blank\">View raw code<\/a><\/p>\n<p><strong>Note:<\/strong> make sure your replace the server variable with your <a href=\"https:\/\/randomnerdtutorials.com\/installing-raspbian-lite-enabling-and-connecting-with-ssh\/\">Raspberry Pi IP address<\/a>:<\/p>\n<pre>const char* server = \"<strong><span style=\"color: #ff0000;\">REPLACE_WITH_YOUR_RASPBERRY_PI_IP_ADDRESS<\/span><\/strong>\";<\/pre>\n<h4>Modifying the code for your project<\/h4>\n<p>In this example, the Arduino performs an HTTP POST request to Node-RED, but you could change it to make request another web service or server. We won&#8217;t explain the Arduino code line by line. For this project it&#8217;s important that you understand what you need to change in the Arduino code to encode\/generate a JSON request.<\/p>\n<h4>sendRequest() function<\/h4>\n<p>For this project you can modify the<em><strong> sendRequest()<\/strong> <\/em>function with your own JSON data structure:<\/p>\n<pre>bool <strong>sendRequest<\/strong>(const char* host, const char* resource) {<\/pre>\n<p>Start by reserving memory space for your JSON data.&nbsp;You can use <a href=\"https:\/\/arduinojson.org\/v5\/assistant\/\" target=\"_blank\" rel=\"noopener nofollow noreferrer\">ArduinoJson Assistant<\/a>&nbsp;to compute the exact buffer size, but for this example 200 is enough.<\/p>\n<pre>StaticJsonBuffer&lt;200&gt; jsonBuffer;<\/pre>\n<p>Create a JsonObject called root that will hold your data and assign the values to your keys (in this example we have the <strong>sensor<\/strong> key):<\/p>\n<pre>JsonObject&amp; root = jsonBuffer.createObject();\nroot[\"<strong>sensor<\/strong>\"] = \"dht11\";<\/pre>\n<p>To hold data inside an array, you do the following:<\/p>\n<pre>JsonObject&amp; data = root.createNestedObject(\"data\");\ndata.set(\"temperature\", \"30.1\");\ndata.set(\"humidity\", \"70.1\");<\/pre>\n<p>Print the generated JSON string in the Arduino IDE serial monitor for debugging purposes:<\/p>\n<pre><strong>root.printTo(Serial);<\/strong><\/pre>\n<p>The rest of the&nbsp;sendRequest() function is the POST request.<\/p>\n<pre>client.print(\"POST \");\nclient.print(resource);\nclient.println(\" HTTP\/1.1\");\nclient.print(\"Host: \");\nclient.println(host);\nclient.println(\"Connection: close\\r\\nContent-Type: application\/json\");\nclient.print(\"Content-Length: \");\nclient.print(<strong>root.measureLength()<\/strong>);\nclient.print(\"\\r\\n\");\nclient.println();\n<strong>root.printTo(client);<\/strong><\/pre>\n<p>Note that you can use the&nbsp;<strong>root.measureLength()<\/strong> to determine the length of your generated JSON. The&nbsp;root.printTo(client) send the JSON data to the Ethernet client.<\/p>\n<h3>Demonstration<\/h3>\n<p>Open the Arduino IDE serial monitor at a baud rate of 9600 and you&#8217;ll see the JSON object printed in the serial monitor every 60 seconds.<\/p>\n<p><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-42474\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/08\/Arduino-JSON-POST-Arduino-IDE-serial-monitor.png?resize=800%2C357&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"\" width=\"800\" height=\"357\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/08\/Arduino-JSON-POST-Arduino-IDE-serial-monitor.png?w=800&amp;quality=100&amp;strip=all&amp;ssl=1 800w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/08\/Arduino-JSON-POST-Arduino-IDE-serial-monitor.png?resize=300%2C134&amp;quality=100&amp;strip=all&amp;ssl=1 300w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/08\/Arduino-JSON-POST-Arduino-IDE-serial-monitor.png?resize=768%2C343&amp;quality=100&amp;strip=all&amp;ssl=1 768w\" sizes=\"(max-width: 800px) 100vw, 800px\" \/><\/p>\n<p>In the Node-RED <strong>debug<\/strong> tab you&#8217;ll see the same JSON object being receive every 60 seconds:<\/p>\n<p><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-42478\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/08\/5_Node-RED_Flow_JSON_POST.png?resize=311%2C274&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"\" width=\"311\" height=\"274\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/08\/5_Node-RED_Flow_JSON_POST.png?w=311&amp;quality=100&amp;strip=all&amp;ssl=1 311w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/08\/5_Node-RED_Flow_JSON_POST.png?resize=300%2C264&amp;quality=100&amp;strip=all&amp;ssl=1 300w\" sizes=\"(max-width: 311px) 100vw, 311px\" \/><\/p>\n<p>Finally, you create functions in Node-RED that do something useful with the received data, but for demonstration purposes we&#8217;re just printing the sample data.<\/p>\n<h2>Wrapping up<\/h2>\n<p>In this tutorial we\u2019ve shown you several examples on how to decode and encode JSON data. You can follow these basic steps to build more advanced projects that require exchanging data between devices.<\/p>\n<p>We hope you\u2019ve found this tutorial useful.<\/p>\n<p>If you liked this project and Home Automation make sure you check our course: <a href=\"https:\/\/randomnerdtutorials.com\/build-a-home-automation-system-for-100\/\">Build a Home Automation System for $100<\/a>.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>In this blog post you&#8217;re going to learn how to decode (parse a JSON string) and encode (generate a JSON string) with the ArduinoJson library using the Arduino with the &#8230; <\/p>\n<p class=\"read-more-container\"><a title=\"Decoding and Encoding JSON with Arduino or ESP8266\" class=\"read-more button\" href=\"https:\/\/randomnerdtutorials.com\/decoding-and-encoding-json-with-arduino-or-esp8266\/#more-42247\" aria-label=\"Read more about Decoding and Encoding JSON with Arduino or ESP8266\">CONTINUE READING \u00bb<\/a><\/p>\n","protected":false},"author":1,"featured_media":42498,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"jetpack_post_was_ever_published":false,"_jetpack_newsletter_access":"","_jetpack_dont_email_post_to_subs":false,"_jetpack_newsletter_tier_id":0,"_jetpack_memberships_contains_paywalled_content":false,"_jetpack_memberships_contains_paid_content":false,"footnotes":""},"categories":[267,2,300,269,264,10],"tags":[],"class_list":["post-42247","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-arduino-project","category-arduino","category-0-esp8266","category-guide-project","category-project","category-a-tutorials"],"aioseo_notices":[],"jetpack_featured_media_url":"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/08\/Arduino-JSON-featured-image.png?fit=1146%2C588&quality=100&strip=all&ssl=1","jetpack_sharing_enabled":true,"_links":{"self":[{"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/posts\/42247","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/comments?post=42247"}],"version-history":[{"count":0,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/posts\/42247\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/media\/42498"}],"wp:attachment":[{"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/media?parent=42247"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/categories?post=42247"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/tags?post=42247"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}