JSON Picker

by 11je in Circuits > Arduino

236 Views, 1 Favorites, 0 Comments

JSON Picker

JSON_Picker.png

With API request you can import a lot of data into your Arduino-projects, from dictionaries, trafic, stockmarket, etc. See also : any-api.com

In this ESP8266 example we take one value out of the (large) Openweathermap.org JSON string. For instance, if the humidity outsite is high, we want to open the window of our greenhouse. You then need only one value. In that case this Arduinofunction will do.

Of course you can change this sketch for a lot of other purpose.

Wifi-connection

We use the familiar wifi-login as shown below.

#include "ESP8266WiFi.h"

const char* ssid = "ssid"; //Enter SSID
const char* password = "password"; //Enter Password

void setup(void)
{ 
  Serial.begin(115200);
  // Connect to WiFi
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) 
  {
     delay(500);
     Serial.print("*");
  }
  
  Serial.println("");
  Serial.println("WiFi connection Successful");
  Serial.print("The IP Address of ESP8266 Module is: ");
  Serial.print(WiFi.localIP());// Print the IP address
}

void loop() 
{
  // EMPTY
}

Adding HTTPclient

We need the HTTP-ckient library:

#include <ESP8266HTTPClient.h> 

And the way to make a request:

Later on we put it in a function .

HTTPClient http;                                        // Use library for HTTPClient<br>http.begin(API_http);
int httpCode = http.GET();                          // send the request and return errorcode. 
if (httpCode > 0) {                                 // check the returning code > 0 is oké
  String RequestAnswer = http.getString();          //Get the request response RequestAnswer
  http.end();                                       //Close connection
}
else {                                              //if request failes:<br>  Serial.print("http error code = ");<br>  Serial.print(httpCode);<br>  Serial.print(http.errorToString(httpCode).c_str());<br>}

After closing the HTTP connection we have the JSON-data in a string named: RequestAnswer for later processing.

Extract Correct Data

You need to open the JSON in a web-browser or in the serial monitor to look for the name of your data you need. The sketch-part below will do the follow:

  1. looking for the position of the name you have given.
  2. remove everything before that possession
  3. looking for the end of the name you have given
  4. delighting the name from so that the correct data is the beginning of our string
  5. looking for the end of our data That is were a ":" of "}" is found
  6. removing everything after your data
  7. change data from string to float.
int startPos = RequestAnswer.indexOf(ValueName);      //Position of valuename <br>            //Serial.print("httprequest oké and return = ");'// uncommad this three lines to see the JSON in your Serial Monitor.
            //Serial.println(RequestAnswer);
            //Serial.print(ValueName); Serial.print(" found at: "); Serial.println(startPos);
RequestAnswer=RequestAnswer.substring(startPos+1);      //Everything before we true away
startPos=RequestAnswer.indexOf(":");                    //end of valuename and the begin of value
RequestAnswer=RequestAnswer.substring(startPos+1);      //true away valuename from string
          
int endPos1=RequestAnswer.indexOf(","); 
int endPos2=RequestAnswer.indexOf("}");
      // abort at smallest to determine end position and separate the value
if (endPos1<endPos2){<br>  RequestAnswer=RequestAnswer.substring(0,endPos1);   //everything behind it away<br>  }

else{<br>  RequestAnswer=RequestAnswer.substring(0,endPos2);<br>  }<br>float ValueWaarde = RequestAnswer.toFloat(); <br>              //Serial.print( "the found value for ");    //uncommand this four lines to see the value in your serial monitor<br>              //Serial.print(ValueName);<br>              //Serial.print(" is : ");<br>              //Serial.println(ValueWaarde);<br>return ValueWaarde;<br><endpos2){        ="" requestanswer="RequestAnswer.substring(0,endPos1);  " nu="" alles="" achter="" de="" waarde="" weggooien="" zpdat="" overblijft=""      ="" }="" else{="" float="" valuewaarde="RequestAnswer.toFloat();"              ="" serial.print(="" "the="" found="" value="" for="" ");   ="" uncommand="" this="" four="" lines="" to="" see="" the="" in="" your="" serial="" monitor="" serial.print(valuename);="" serial.print("="" is="" :="" ");="" serial.println(valuewaarde);="" return="" valuewaarde;<="" p=""></endpos2){>

The Hole Sketch

/* This sketch example shows how to get one simple data uit of an Openweather JSON string. 
* You need to create an account by openweathermap.org for the key.
* This example can by modify for other site's or fields.
* If you need more fields out of one JSON, this sketch is not handy, but easely to modify
* by opening once and let the "RequestAnswer" compleet.
* This sketch was made by Laurens Korste from BOKTORROBOTICA.NL and can be used freely.
*/
//#include <WiFi.h> //use this line for ESP32
#include <ESP8266WiFi.h> //use this line for ESP8266
#include <ESP8266HTTPClient.h> // http web access library

const char* ssid = "enter_your_ssid";
const char* password = "enter_your_password";

// make an account by openweather for the key
char API_http[]= "http://api.openweathermap.org/data/2.5/weather?q=assen,nl&units=metric&appid=PUT_YOUR_ONE_KEY_HERE";

void setup()
{
Serial.begin(115200);
Serial.println();

WiFi.begin(ssid, password);

Serial.print("Connecting");
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println();

Serial.print("Connected, IP address: ");
Serial.println(WiFi.localIP());
}

void loop() { // Change "humidity" in the value you like to have. Look into the JSON for the right name. (only the first will be taken.)
float Value = GetValueJson("humidity"); //Uit de JSON wordt de variabele "temp" opgevraagd.
Serial.print ("Value = ");
Serial.println(Value);
delay(120*1000); // 2 minuten tijd tussen HTTP request. (Liever geen delay gebruiken.)
}

float GetValueJson(char ValueName[]){
if (WiFi.status() != WL_CONNECTED) { //Check WiFi connection status
Serial.println("Wifi-connectie failed"); //No WiFi connection. You can upgrade this part of the sketch to make a new connection or to reset the ESP.
}else
{
Serial.println();
Serial.println("GetVaueJSON : Wifi.status = connect, http request start ");
HTTPClient http; // Use library for HTTPClient
http.begin(API_http);
int httpCode = http.GET(); // send the request and return errorcode.
if (httpCode > 0) { // check the returning code > 0 is oké
String RequestAnswer = http.getString(); //Get the request response RequestAnswer
http.end(); //Close connection

// Now we have the JSON in RequestAnswer. Now we can search for the data we need.
int startPos = RequestAnswer.indexOf(ValueName); //Position of valuename
//Serial.print("httprequest oké and return = ");'// uncommad this three lines to see the JSON in your Serial Monitor.
//Serial.println(RequestAnswer);
//Serial.print(ValueName); Serial.print(" found at: "); Serial.println(startPos);
RequestAnswer=RequestAnswer.substring(startPos+1); //Everything before we true away
startPos=RequestAnswer.indexOf(":"); //end of valuename and the begin of value
RequestAnswer=RequestAnswer.substring(startPos+1); //true away valuename from string

int endPos1=RequestAnswer.indexOf(",");
int endPos2=RequestAnswer.indexOf("}");
// abort at smallest to determine end position and separate the value
if (endPos1<endPos2){
RequestAnswer=RequestAnswer.substring(0,endPos1); //nu alles achter de waarde weggooien zpdat waarde overblijft
}
else{
RequestAnswer=RequestAnswer.substring(0,endPos2);
}
float ValueWaarde = RequestAnswer.toFloat();
//Serial.print( "the found value for "); //uncommand this four lines to see the value in your serial monitor
//Serial.print(ValueName);
//Serial.print(" is : ");
//Serial.println(ValueWaarde);
return ValueWaarde;
}
else { //if request failes:
Serial.print("http error code = ");
Serial.print(httpCode);
Serial.print(http.errorToString(httpCode).c_str());
}
}
}