Extracting info from a JSON return

I am using an ESP8266 chip & doing a http Post to my REST API server.

int httpCode = http.POST(json); // Send the request

String payload = http.getString(); // Get the response Serial.print("httpCode = "); Serial.println(httpCode); // Print HTTP return code Serial.print("Payload = "); Serial.println(payload); // Print request response payload Serial.print("Stuff here = "); Serial.println(""); http.end(); // Close connection

I am receiving a response back from the API which is giving me a httpCode (of say 201, 400 or -11(?)) & the payload is being output as the following example:

{"code":141,"error":"Device has a different MAC address."}

I now want to extract the code element into a variable which I will output below "Stuff Here". I've tried http.getString(code), but this isn't the right syntax & I get an error.

How would I do this?

Thanks

I now want to extract the code element into a variable

The "code element" has a name and a value ("code" and 141). Which do you want in the variable?

There is a JSON parser library for the Arduino...

Hi,

I'm looking for the value (in my example 141).

Thanks

Presumably this is the parser you're referring to?

https://github.com/bblanchon/ArduinoJson

thomascoope: Presumably this is the parser you're referring to?

https://github.com/bblanchon/ArduinoJson

Yes.

Ace! Figured it. Thanks for your help.

I did it with the following code (having installed the ArduinoJSON library quoted above):

// Add the library
#include <ArduinoJson.h>

// Code (after JSON submission

StaticJsonBuffer<500> jsonBuffer;

JsonObject& root = jsonBuffer.parseObject(http.getString());

const char* code = root[“code”];

Serial.print("Code return element = ");
Serial.println(code);

const char* code = root["code"];

What you are getting is the value of the code element. It would be better to use a name like codeValue to reflect that.

And, of course, your print() statement should reflect that, rather than looking like a patch up of the example. 8)

Understood. I've done this now. Thank you greatly for your assistance.