Arduino Forum

Using Arduino => Programming Questions => Topic started by: Chr1s on Jun 17, 2013, 06:34 pm

Title: JSON Library?
Post by: Chr1s on Jun 17, 2013, 06:34 pm
Hi all,

Given the recent changes in the twitter APIs - they have deprecated their 1.0 API which offered REST and now they're enforcing 1.1 which has only support for JSON - I'm looking for a decent and functionning JSON Library for Arduino. I've read about a quite old project called aJSON but it seems to be dead since 2010 and there's no download available: the github account linked from the article is empty.

Do you guys have a recommendation for me?

Thanks in advance!
Christophe
Title: Re: JSON Library?
Post by: nicoverduin on Jun 17, 2013, 07:52 pm
It's a start : https://github.com/not404/json-arduino
Title: Re: JSON Library?
Post by: JacobChrist on Sep 17, 2013, 12:32 am
There is a json lib here that my colleage wrote for chipKIT (Microchip PIC32 Arduino Compatible boards).  It may work with Arduino.  At its core it makes calls to Arduino libs used in chipKIT.  I believe it does make use of malloc, which from my understanding does not work so great on Arduino.  Its maintained and used heavily but not documented.

https://github.com/pontech/pic32lib

Jacob
Title: Re: JSON Library?
Post by: Leonzio on Nov 19, 2013, 05:39 pm
I don't know if this is something you still need, but aJson seems to be available on Github.
See the project homepage here: http://interactive-matter.eu/how-to/ajson-arduino-json-library/

Regards
Andrea
Title: Re: JSON Library?
Post by: Leonzio on Nov 19, 2013, 05:47 pm
For some reasons, the Github link from the page I've linked before gives an empty repository.
You can find the aJson library here:
https://github.com/interactive-matter/aJson

Regards
Andrea
Title: Re: JSON Library?
Post by: BenoitB on Jan 20, 2014, 02:05 pm
I was not satisfied with "aJson" and "json-arduino" because both of them rely on malloc() and therefore doesn't perform well in very low memory conditions.

So I wrote my own "malloc-free JSON parser":
https://arduinojson.org
Title: Re: JSON Library?
Post by: alfio76 on Feb 04, 2014, 07:54 am
Hello,
i try your library but the parsing not extract the name the age etc etc.
Title: Re: JSON Library?
Post by: PaulS on Feb 04, 2014, 12:28 pm

Hello,
i try your library but the parsing not extract the name the age etc etc.

Fail. You're going to have to do much better than that. It doesn't extract what information from what? Be very specific!
Title: Re: JSON Library?
Post by: gbathree on Feb 05, 2014, 09:02 pm
Hey BenoitB - thanks for making that library!

I've tried running the example in the jsonparser library on a Teensy 3.0 and Teensy 3.1, however, and can't get the ParseAnObject() subroutine to complete successfully (this calls the hashTable.getString, hashTable.getArray... or other hashTable commands).  The array.getArray command works fine, and the ParseAnArray() subroutine runs fine.  I have managed to get ParseAnObject() subroutine to successfully complete on an Arduino Uno and Teensy 2.0, however, so it must be some compatability issue with 3.0 and 3.1 (ARM perhaps??). 

There's no compile errors, but the program simply stops at line 25 when it runs .getString for the first time. 

Code: [Select]
char* name = hashTable.getString("Name");

So, to be clear and perhaps too obvious, the output looks like this:

Parse {"Name":"Blanchon","Skills":["C","C++","C#"],"Age":32,"Online":true}

I tried commenting out getString and attempting the getArray and getLong and they also do not work.  I also tried explicitely adding the following libraries to the top of the file...

Code: [Select]
#include <JsonParser.h>
#include "utility/jsmn.h"
#include <stdlib.h> // for strtol, strtod
#include <string.h> // for strcmp()
#include "JsonObjectBase.h"
#include "JsonHashTable.h"
#include "JsonArray.h"


seems silly but I've had previous examples (Adafruit's sensor library) not compile without explicitely adding the AdafruitSensor.h library to the top of my .ino file (even though it was referenced in the library .h file...).  Anyway, that didn't work either.

Any ideas?

Greg
Title: Re: JSON Library?
Post by: jflaplante on Feb 17, 2014, 08:11 pm

I was not satisfied with "aJson" and "json-arduino" because both of them rely on malloc() and therefore doesn't perform well in very low memory conditions.

So I wrote my own "malloc-free JSON parser":
https://github.com/bblanchon/ArduinoJsonParser


I tried the first two before trying your library.  I always ran into memory problem after a while.  I have no such problem so far with your library.   It is working perfectly with my web services.

Thanks Benoit for a very well polished product!

Jean-Francois.
Title: Re: JSON Library?
Post by: gbathree on Feb 25, 2014, 07:21 pm
I'm having an issue pulling all of the tokens from a JSON - I can get some of them, but not others.  I'm using a Teensy 3.1 with 64K SRAM.

Here's two JSONs I've tested.  In both case, the last few tokens are not parsed.  Thinking it was a problem with the length of the JSON, I tried the 2nd JSON which is <32 tokens, so it's fairly small but still has the same issue:

-- does not parse measlights, measlights2, altc, and altd
Code: [Select]

{"protocol_name":"fluorescence","repeats":1,"wait":0,"averages":1,"measurements":3,"meas2_light":15,"meas1_baseline":0,"act_light":20,"pulsesize":25,"pulsedistance":10000,"actintensity1":50,"actintensity2":255,"measintensity":255,"calintensity":255,"pulses":[50,50,50],"act":[2,1,2,2],"red":[2,2,2,2],"detectors":[[34,34,34,34],[34,34,34,34],[34,34,34,34],[34,34,34,34]],"alta":[2,2,2,2],"altb":[2,2,2,2],"measlights":[[15,15,15,15],[15,15,15,15],[15,15,15,15],[15,15,15,15]],"measlights2":[[15,15,15,15],[15,15,15,15],[15,15,15,15],[15,15,15,15]],"altc":[2,2,2,2],"altd":[2,2,2,2]}


-- does not parse altc and altd
Code: [Select]

{"measlights":[[15],[15],[15],[15]],"end":[[15],[15],[15],[15]],"alta":[2,2],"altb":[2,2],"altc":[2,2],"altd":[2,2]}


I can't seem to get those last few values to be parsed correctly.  And it's always the last few values - if you switch the order of the tokens, it's always the ones at the end which aren't parsed.  It makes me think it's a memory issue, but I know that's not the case, the program is small and there's plenty of memory left.  I've messed around with lots of things, like changing the JsonParser size, changing the varaible names, moving them around within the JSON itself, calling the values in a different way... but haven't been able to figure it out.

Any suggestions, ideas, or similar problems?

See attached for the code I used to test.  Just enter any number followed by the JSON in the serial com window to parse (one of the above 2).  It tries to find the variables it's looking for, it prints their values if they are found.  
Title: Re: JSON Library?
Post by: BenoitB on Feb 27, 2014, 01:59 pm
Hi gbathree,

Sorry for making you wait so long.

About your first post.
There was a mistake in the sample code.
You need to replace char* json by char json[].
It was generating an access violation because the memory was write protected and the parser needs to alter the string.
I didn't see that on Arduino because there is no memory protection.

About your second post.
You are right: there was a bug in the parser's code.
The bug occurred as soon as the JSON string contains a multi-dimensional array.
I fixed it in the master branch, you can download it at:
https://github.com/bblanchon/ArduinoJson
Please keep me informed.

Regards,
Benoit
Title: Re: JSON Library?
Post by: gbathree on Feb 27, 2014, 02:41 pm
Confirmed - works great now!  Thanks so much - this is an awesome library!  If you want to see what we're doing with it - the project is located at www.photosynq.org.

Greg
Title: Re: JSON Library?
Post by: hithwen on Apr 06, 2014, 10:07 am
Hi, this other library goes one step beyond than bblanchon one. Apart form not doing mallocs it does not need to have the whole json string in memory, it receives a Stream and reads it char by char because sometime just the json string is too big. It is called StreamJsonReader (https://www.biicode.com/lasote/blocks/lasote/stream_json_reader/branches/master#.U0EMTuZ_tUk).  Here's a blog post (http://web.biicode.com/blog/big-json-on-arduino) about the motivation and a little example  
Title: Re: JSON Library?
Post by: Roost on May 20, 2014, 05:30 pm
ArduinoJsonParser looks like a great library BenoitB, well done.

Something I have noticed that I cant seem to get fixed. This library doesn't seem to parse tiered objects that are not array types. I am trying to parse something like the following;

Code: [Select]
{"method":"methodname","params":{"id":"fdtf5ere","status":4}}

I can successfully extract the "method" key, and can validate the "params" key with

Code: [Select]
hashTable.containsKey("params")

I have tried to extract the params hashTable with

Code: [Select]
JsonHashTable paramsTable = hashTable.getHashTable("params");

but that also seems to fail. Am I missing something, or is this a fault?

Cheers.
Bruce
Title: Re: JSON Library?
Post by: Roost on May 20, 2014, 06:36 pm
As is always the case.

After stepping away for 10 minutes, and rechecking everything, it appears I made the mistake as mentioned

"char* json by char json[]"

Changing that, and all is now working as expected.

Thanks
Bruce
Title: Re: JSON Library?
Post by: nicoverduin on Aug 25, 2014, 07:42 pm
No doubt it is me  :smiley-mr-green: But, I tried to compile this example under Eclipse using Arduino IDE 1.5.2 and Jantjes plugin and I am getting a bunch of linker errors :
Code: [Select]

Starting combiner
"D:/Arduino/hardware/tools/avr/bin/avr-gcc" -Os -Wl,--gc-sections -mmcu=atmega328p -o "D:/workspace/ArduinoJsonTest/Release/ArduinoJsonTest.elf"    ./ArduinoJsonTest.cpp.o  ./Libraries/ArduinoJson/JsonGenerator/EscapedString.cpp.o ./Libraries/ArduinoJson/JsonGenerator/JsonArrayBase.cpp.o ./Libraries/ArduinoJson/JsonGenerator/JsonObjectBase.cpp.o ./Libraries/ArduinoJson/JsonGenerator/JsonValue.cpp.o ./Libraries/ArduinoJson/JsonGenerator/Print.cpp.o ./Libraries/ArduinoJson/JsonGenerator/StringBuilder.cpp.o  ./Libraries/ArduinoJson/JsonGenerator.cpp.o   D:/workspace/ArduinoJsonTest/Release/arduino.ar   "D:/workspace/ArduinoJsonTest/Release/arduino.ar" "-LD:/workspace/ArduinoJsonTest/Release" -lm
./Libraries/ArduinoJson/JsonGenerator.cpp.o: In function `ArduinoJson::Generator::JsonArrayBase::printTo(Print&) const':
D:/Documents/Arduino/libraries/ArduinoJson/JsonGenerator/JsonArrayBase.cpp:11: multiple definition of `ArduinoJson::Generator::JsonArrayBase::printTo(Print&) const'
./Libraries/ArduinoJson/JsonGenerator/JsonArrayBase.cpp.o:D:/Documents/Arduino/libraries/ArduinoJson/JsonGenerator/JsonArrayBase.cpp:11: first defined here
./Libraries/ArduinoJson/JsonGenerator.cpp.o: In function `ArduinoJson::Internals::StringBuilder::write(unsigned char)':
D:/Documents/Arduino/libraries/ArduinoJson/JsonGenerator/StringBuilder.cpp:10: multiple definition of `ArduinoJson::Internals::StringBuilder::write(unsigned char)'
./Libraries/ArduinoJson/JsonGenerator/StringBuilder.cpp.o:D:/Documents/Arduino/libraries/ArduinoJson/JsonGenerator/StringBuilder.cpp:10: first defined here
./Libraries/ArduinoJson/JsonGenerator.cpp.o: In function `ArduinoJson::Generator::JsonValue::printPrintableTo(ArduinoJson::Generator::JsonValue::Content const&, Print&)':
D:/Documents/Arduino/libraries/ArduinoJson/JsonGenerator/JsonValue.cpp:22: multiple definition of `ArduinoJson::Generator::JsonValue::printPrintableTo(ArduinoJson::Generator::JsonValue::Content const&, Print&)'
./Libraries/ArduinoJson/JsonGenerator/JsonValue.cpp.o:D:/Documents/Arduino/libraries/ArduinoJson/JsonGenerator/JsonValue.cpp:22: first defined here
./Libraries/ArduinoJson/JsonGenerator.cpp.o: In function `ArduinoJson::Generator::JsonValue::printBoolTo(ArduinoJson::Generator::JsonValue::Content const&, Print&)':
D:/Documents/Arduino/libraries/ArduinoJson/JsonGenerator/JsonValue.cpp:12: multiple definition of `ArduinoJson::Generator::JsonValue::printBoolTo(ArduinoJson::Generator::JsonValue::Content const&, Print&)'
./Libraries/ArduinoJson/JsonGenerator/JsonValue.cpp.o:D:/Documents/Arduino/libraries/ArduinoJson/JsonGenerator/JsonValue.cpp:12: first defined here
./Libraries/ArduinoJson/JsonGenerator.cpp.o: In function `ArduinoJson::Internals::EscapedString::printTo(char const*, Print&)':
D:/Documents/Arduino/libraries/ArduinoJson/JsonGenerator/EscapedString.cpp:33: multiple definition of `ArduinoJson::Internals::EscapedString::printTo(char const*, Print&)'
./Libraries/ArduinoJson/JsonGenerator/EscapedString.cpp.o:D:/Documents/Arduino/libraries/ArduinoJson/JsonGenerator/EscapedString.cpp:33: first defined here
./Libraries/ArduinoJson/JsonGenerator.cpp.o: In function `ArduinoJson::Generator::JsonValue::printStringTo(ArduinoJson::Generator::JsonValue::Content const&, Print&)':
D:/Documents/Arduino/libraries/ArduinoJson/JsonGenerator/JsonValue.cpp:30: multiple definition of `ArduinoJson::Generator::JsonValue::printStringTo(ArduinoJson::Generator::JsonValue::Content const&, Print&)'
./Libraries/ArduinoJson/JsonGenerator/JsonValue.cpp.o:D:/Documents/Arduino/libraries/ArduinoJson/JsonGenerator/JsonValue.cpp:30: first defined here
./Libraries/ArduinoJson/JsonGenerator.cpp.o: In function `ArduinoJson::Generator::JsonObjectBase::printTo(Print&) const':
D:/Documents/Arduino/libraries/ArduinoJson/JsonGenerator/JsonObjectBase.cpp:14: multiple definition of `ArduinoJson::Generator::JsonObjectBase::printTo(Print&) const'
./Libraries/ArduinoJson/JsonGenerator/JsonObjectBase.cpp.o:D:/Documents/Arduino/libraries/ArduinoJson/JsonGenerator/JsonObjectBase.cpp:14: first defined here
./Libraries/ArduinoJson/JsonGenerator.cpp.o: In function `ArduinoJson::Generator::JsonValue::printLongTo(ArduinoJson::Generator::JsonValue::Content const&, Print&)':
D:/Documents/Arduino/libraries/ArduinoJson/JsonGenerator/JsonValue.cpp:17: multiple definition of `ArduinoJson::Generator::JsonValue::printLongTo(ArduinoJson::Generator::JsonValue::Content const&, Print&)'
./Libraries/ArduinoJson/JsonGenerator/JsonValue.cpp.o:D:/Documents/Arduino/libraries/ArduinoJson/JsonGenerator/JsonValue.cpp:17: first defined here
./Libraries/ArduinoJson/JsonGenerator.cpp.o: In function `ArduinoJson::Generator::JsonObjectBase::getMatchingPair(char const*) const':
D:/Documents/Arduino/libraries/ArduinoJson/JsonGenerator/JsonObjectBase.cpp:42: multiple definition of `ArduinoJson::Generator::JsonObjectBase::getMatchingPair(char const*) const'
./Libraries/ArduinoJson/JsonGenerator/JsonObjectBase.cpp.o:D:/Documents/Arduino/libraries/ArduinoJson/JsonGenerator/JsonObjectBase.cpp:42: first defined here
./Libraries/ArduinoJson/JsonGenerator.cpp.o: In function `ArduinoJson::Generator::JsonObjectBase::remove(char const*)':
D:/Documents/Arduino/libraries/ArduinoJson/JsonGenerator/JsonObjectBase.cpp:86: multiple definition of `ArduinoJson::Generator::JsonObjectBase::remove(char const*)'
./Libraries/ArduinoJson/JsonGenerator/JsonObjectBase.cpp.o:D:/Documents/Arduino/libraries/ArduinoJson/JsonGenerator/JsonObjectBase.cpp:86: first defined here
./Libraries/ArduinoJson/JsonGenerator.cpp.o: In function `ArduinoJson::Generator::JsonObjectBase::containsKey(char const*) const':
D:/Documents/Arduino/libraries/ArduinoJson/JsonGenerator/JsonObjectBase.cpp:83: multiple definition of `ArduinoJson::Generator::JsonObjectBase::containsKey(char const*) const'
./Libraries/ArduinoJson/JsonGenerator/JsonObjectBase.cpp.o:D:/Documents/Arduino/libraries/ArduinoJson/JsonGenerator/JsonObjectBase.cpp:83: first defined here
./Libraries/ArduinoJson/JsonGenerator.cpp.o: In function `ArduinoJson::Generator::JsonObjectBase::operator[](char const*)':
D:/Documents/Arduino/libraries/ArduinoJson/JsonGenerator/JsonObjectBase.cpp:57: multiple definition of `ArduinoJson::Generator::JsonObjectBase::operator[](char const*)'
./Libraries/ArduinoJson/JsonGenerator/JsonObjectBase.cpp.o:D:/Documents/Arduino/libraries/ArduinoJson/JsonGenerator/JsonObjectBase.cpp:57: first defined here
./Libraries/ArduinoJson/JsonGenerator.cpp.o:(.bss._ZN11ArduinoJson9Generator14JsonObjectBase9nullValueE+0x0): multiple definition of `ArduinoJson::Generator::JsonObjectBase::nullValue'
./Libraries/ArduinoJson/JsonGenerator/JsonObjectBase.cpp.o:D:/Documents/Arduino/libraries/ArduinoJson/JsonGenerator/JsonObjectBase.cpp:42: first defined here
make: *** [ArduinoJsonTest.elf] Error 1


The example is this one:
Code: [Select]

/*
* Arduino JSON library - Generator example
* Benoit Blanchon 2014 - MIT License
*/

#include "Arduino.h"
#include <JsonGenerator.h>

using namespace ArduinoJson::Generator;

void setup()
{
   Serial.begin(9600);

   JsonArray<2> array;
   array.add<6>(48.756080); // 6 is the number of decimals to print
   array.add<6>(2.302038);  // if not specified, 2 digits are printed

   JsonObject<3> root;
   root["sensor"] = "gps";
   root["time"] = 1351824120;
   root["data"] = array;

   Serial.print(root); // {"sensor":"gps","time":1351824120,"data":[48.756080,2.302038]}
}

void loop()
{

}


Any tips where I missed the boat :smiley-mr-green:

@edit: This is interesting. If I compile it direct in the IDE 1.5.2 it works fine....
Title: Re: JSON Library?
Post by: BenoitB on Sep 01, 2014, 10:05 pm
I think I know what's going on here...

To make the library work properly with the Arduino IDE, I added 4 files at the root:


If you open them, you'll see that they only contain #include of the files in the subfolders.
That's a workaround for the Arduino IDE, because it doesn't look for files in the subfolders.

Unfortunately for you, Eclipse does   :P
I suggest you remove the two .cpp files at the root or exclude them from the build.
Title: Re: JSON Library?
Post by: nicoverduin on Sep 02, 2014, 10:48 pm
Thanks

That solved the problem  :smiley-mr-green:

Nice library  :smiley-mr-green:

Nico
Title: Re: JSON Library?
Post by: GUNASEELAN on Nov 26, 2014, 07:03 am
In Arduino how to use both json generator and parser library in a single sketch ?

While i use ,
#include <JsonGenerator.h>
#include <JsonParser.h>

It throws errors stating,

"ArduinoJsonParser\utility\jsmn.cpp.o: In function `jsmn_parse(jsmn_parser*, char const*, jsmntok_t*, unsigned int)':
C:\Users\Guna Qruize\Documents\Arduino\libraries\ArduinoJsonParser\utility/jsmn.cpp:135: multiple definition of `jsmn_parse(jsmn_parser*, char const*, jsmntok_t*, unsigned int)'
ArduinoJson\JsonParser.cpp.o:C:\Users\Guna Qruize\Documents\Arduino\libraries\ArduinoJson\/JsonParser/jsmn.cpp:135: first defined here
ArduinoJsonParser\utility\jsmn.cpp.o: In function `jsmn_init(jsmn_parser*)':
C:\Users\Guna Qruize\Documents\Arduino\libraries\ArduinoJsonParser\utility/jsmn.cpp:250: multiple definition of `jsmn_init(jsmn_parser*)'
ArduinoJson\JsonParser.cpp.o:C:\Users\Guna Qruize\Documents\Arduino\libraries\ArduinoJson\/JsonParser/jsmn.cpp:250: first defined here"
Title: Re: JSON Library?
Post by: nickgammon on Nov 26, 2014, 07:41 am
The cross-posting is strong in this one.

http://forum.arduino.cc/index.php?topic=281554.0 (http://forum.arduino.cc/index.php?topic=281554.0)

@Gunaseelan: When you didn't get a response within 2 minutes, you just decided to post again, is that it? And that was only 30 minutes after your own thread?

Have you not considered that the person who might be able to help is asleep? And might be for another 8 hours?
Title: Re: JSON Library?
Post by: Coding Badly on Nov 26, 2014, 08:32 am
The cross-posting is strong in this one.
Very strong...
http://forum.arduino.cc/index.php?topic=281557.0 (http://forum.arduino.cc/index.php?topic=281557.0)
Title: Re: JSON Library?
Post by: nickgammon on Nov 26, 2014, 09:05 am
Maybe we should ban him?
Title: Re: JSON Library?
Post by: nickgammon on Nov 26, 2014, 09:31 am
Well, it looks like I misquoted.

Quote
The cross-posting is strong in with this one.
Title: Re: JSON Library?
Post by: acasado on Jan 09, 2015, 11:21 am
Benoit et al:

I am trying to use this library, it looks cool and it is well documented.
It works for me on plain JSON strings, however I wonder how to use it on nested objects (curly braces inside curly braces), it parses ok, at least no errors, however I wonder how to get an object inside another objects.
In the below example, I need to get the temp, pressure and humidity.

See this example:

output from:  http://api.openweathermap.org/data/2.5/weather?id=3117735

The ArduinoJson pretty print output is:

{
  "coord": {
    "lon": -3.7,
    "lat": 40.42
  },
  "sys": {
    "message": 0.0401,
    "country": "ES",
    "sunrise": 1420789051,
    "sunset": 1420823192
  },
  "weather": [
    {
      "id": 800,
      "main": "Clear",
      "description": "Sky is Clear",
      "icon": "01d"
    }
  ],
  "base": "cmc stations",
  "main": {
    "temp": 271.744,
    "temp_min": 271.744,
    "temp_max": 271.744,
    "pressure": 980.94,
    "sea_level": 1058.7,
    "grnd_level": 980.94,
    "humidity": 71
  },
  "wind": {
    "speed": 1.51,
    "deg": 20.5025
  },
  "clouds": {
    "all": 0
  },
  "dt": 1420797371,
  "id": 3117735,
  "name": "Madrid",
  "cod": 200
}


and the ArduinoJson iteration of value key pairs is:

coord =>
sys =>
weather =>
base => cmc stations
main =>
wind =>
clouds =>
dt =>
id =>
name => Madrid
cod =>
sys.sunrise =>
sunset =>
pressure =>
humidity =>


Thanks in advance for your help.
AC/.
Title: Re: JSON Library?
Post by: acasado on Jan 09, 2015, 04:22 pm
Folks,
I found the answer myself and the solution is very cool indeed. It is to create some other objects based on the previous objects, cleaver the implementation indeed.
My congratulations for the great implementation.
See my excerpts of how I solved it.
Cheers.
AC/.

// =========================== Get the JSON objects ============
  JsonObject& root = jsonBuffer.parseObject(json);
 
  if (!root.success()) {
    Serial.println("parseObject() failed");
    delay(10000);
    return;
    }
  Serial.println();
  if (Debug)
    root.prettyPrintTo(Serial);                    // print it on prettyPrint format
  Serial.println();
  JsonObject& sys      = root["sys"];           // create the object sys inside of root
  JsonArray&  weather  = root["weather"]; // weather is an array of objects
  JsonObject& wea      = weather[0];         // we care only for the first object, the main weather station
  JsonObject& main     = root["main"];      // main is the main objct on the weather observations
 
  MADsunrise  = sys["sunrise"];                // get the sunrise time on time_t format
  MADsunset   = sys["sunset"];
  MADdesc     = wea["description"];
  MADbase     = root["name"];
  MADtemp     = main["temp"];
  MADpressure = main["pressure"];
  MADhumidity = main["humidity"];
  MADtemp    -= 273.15;                   // from kelvin to degree celsius
  // =========================== Done ===============================
Title: Re: JSON Library?
Post by: riadanza on Jul 14, 2015, 09:15 pm
I'm trying to figure out a way to construct a JSON document with nested string value pairs.  The below example you can see "phoneNumber" is a nested array with string value pairs, this is unlike the example where you have a nested array named "data" then just the values without tags.  Is there a way to do this with this library?

Any help is much appreciated.

{
  "firstName": "John",
  "lastName": "Smith",
  "isAlive": true,
  "age": 25,
  "address": {
    "streetAddress": "21 2nd Street",
    "city": "New York",
    "state": "NY",
    "postalCode": "10021-3100"
  },
  "phoneNumbers": [
    {
      "type": "home",
      "number": "212 555-1234"
    },
    {
      "type": "office",
      "number": "646 555-4567"
    }
  ],
  "children": [],
  "spouse": null
}
Title: Re: JSON Library?
Post by: PaulS on Jul 15, 2015, 11:31 am
Quote
The below example you can see "phoneNumber" is a nested array with string value pairs
Actually, I can't. I can't see phoneNumber anywhere. I do see phoneNumbers.

Seems to me that storing that data in an XML format would be much simpler.
Title: Re: JSON Library?
Post by: Bertie64 on Jun 08, 2016, 03:46 pm
Resurrecting a fairly old thread I know,  but anyway...

I'm using the 'ArduinoJson' library and it works great, but I have a question that I hope someone can help with.

The JSON representation of my nested objects contains a couple of nested arrays.

I can encode and decode the object just fine but I would like to iterate through the object to output the entire structure.

I am using the JsonObject::iterator (recursively for nested objects) and that all works.

The problem I am having is when I encounter one of the nested arrays during the iteration.

I currently have this:

Code: [Select]
void iterate(JsonObject& json) {
for (JsonObject::iterator it=json.begin(); it!=json.end(); ++it) {
if ((it->value).is<JsonObject&>()) {
iterate(it->value);
} else if ((it->value).is<JsonArray&>()) {
JsonArray& myArray = (it->value).asArray();
int count = sizeof(myArray) / sizeof(myArray[0]);
Serial.print("Key : ");
Serial.print(it->key);
Serial.print(" - Values : ");
for (int i = 0; i < count; ++i) {
Serial.print(myArray[i].asString());
if (i != count - 1) {
Serial.print(", ");
} else {
Serial.println();
}
}
} else {
Serial.print("Key : ");
Serial.print(it->key);
Serial.print(" - Value : ");
Serial.println(it->value.asString());
}
}
}


It all does seem to work except that count always seems to equal 1.

Is there something wrong with this:

Code: [Select]
int count = sizeof(myArray) / sizeof(myArray[0]);

The only arrays I am encoding so far have 3 elements and when I use

Code: [Select]
int count = 3;

I works perfectly and prints the three values correctly.

if I print the values returned for sizeof(myArray) and sizeof(myArray[0]) they both return 4.

It's probably me being a bit dim, but myArray seems to be an array with 3 valid elements.
Not sure where I am going wrong here.

Title: Re: JSON Library?
Post by: PaulS on Jun 08, 2016, 03:55 pm
The JsonArray type is a class that derives from List. List has a size() method. Why not use it?

Code: [Select]
int count = myArray.size();
Title: Re: JSON Library?
Post by: Bertie64 on Jun 08, 2016, 06:24 pm
@PaulS - Thank you!

I spent an hour or two during over the various files without spotting that.  Amazing how much easier it is to find something when you now what you are looking for...
Title: Re: JSON Library?
Post by: PaulS on Jun 08, 2016, 06:33 pm
I've spent the last two weeks trying to collect data from a JSON parser, in a meaningful way, for several different kinds of JSON files. So, I had a fair idea about the types involved, and the inheritance, so it wasn't too difficult to find that the expected class had the expected method.
Title: Re: JSON Library?
Post by: mars000 on Apr 19, 2017, 02:11 pm
hi
the arduino json library is unable to parse the following file. I have validated online that it is a valid json file...any clues as to why it might not be parsing ? it simply crashes my WEMOS MINI

here is my serial output:


{
    "fileversion": 1,
    "date_created": "07April2017",
    "latest_build": "mains.bin",
    "mac_address": "08:dd:0f:1c:2a",
    "data_activated": "TBC",
    "auth_code": "shjkhsjk839903klkkl",
    "blynk_server": "blynk.xxxx.com",
    "hardware" : "wemosmini",

    "sv": {
        "appliance": "mains",
        "flow_sensor": "true",
        "water_sensor": "true",
        "valve": "true",
        "number_valves": 1,
        "type" : "master"
    },
   
    "children": [
        {
            "child" : 1,
            "appliance": "dishwasher",
            "mac_address": "08:dd:0f:1c:2a",
            "auth_code": "shjkhsjk839903klkkl"
        },
        {
            "child": 2,
            "appliance" : "washing_machine",
            "mac_address" : "4c:2a:24:43",
            "auth_code": "jdhjjks88392ui"
        }
    ]
}
waiting for parsing to occur...

Exception (28):
epc1=0x4000bf0e epc2=0x00000000 epc3=0x00000000 excvaddr=0x00000000 depc=0x00000000

ctx: cont
sp: 3ffef7c0 end: 3ffefa30 offset: 01a0

>>>stack>>>
3ffef960:  3fffdad0 3ffef9b0 00000001 40202392 
3ffef970:  3ffef980 3fff124b 3ffef980 0000000a <
3ffef980:  3ffe85b8 00000000 3fff1254 00000800 
3ffef990:  00000000 00000001 3ffee94c 3ffeea08 
3ffef9a0:  3fffdad0 00000000 3ffe8350 4020259d 
3ffef9b0:  00000000 3ffe89e8 00000000 3ffe89e8 
3ffef9c0:  00000000 00000000 ffffffff fe000001 
3ffef9d0:  3ffe8496 00000000 fe01ef35 00000000 
3ffef9e0:  00000000 feefeffe feefeffe feefeffe 
3ffef9f0:  feef0031 feefeffe feefeffe feefeffe 
3ffefa00:  feefeffe feefeffe feefeffe feefeffe 
3ffefa10:  feefeffe feefeffe 3ffeea00 40204018 
3ffefa20:  feefeffe feefeffe 3ffeea10 40100718 
<<<stack<<<

 ets Jan  8 2013,rst cause:2, boot mode:(1,7)