How to use Arduino_JSON methods `hasPropertyEqual` and `filter`

Hello there,

In the application I am currently working on, I am looking into the Arduino_JSON functionality to create a function to save and load application option settings to/from an SD card.

So I created the following test code to test on the ESP32:

#include <Arduino_JSON.h>
#include <SD.h>

const char *input = R"(
{
  "code": "200",
  "message": 0,
  "list": [
    {
      "main": {
        "temp": 3.23,
        "pressure": 1014,
        "humidity": 58
      },
      "weather": {
        "main": "Clear",
        "description": "clear sky"
      },
      "dt": "2020-02-12 09:00:00"
    },
    {
      "main": {
        "temp": 6.09,
        "pressure": 1015,
        "humidity": 48
      },
      "weather": {
        "main": "Clear",
        "description": "clear sky"
      },
      "dt": "2020-02-12 12:00:00"
    }
  ],
  "city": {
    "name": "London",
    "coord": {
      "lat": 51.5085,
      "lon": -0.1257
    }
  }
}
)";

void Test_hasOwnProperty(JSONVar &obj) {
  Serial.println("===== Test_hasOwnProperty =====");
  Serial.println(obj.hasOwnProperty("code"));             // (1) 1 ... OK
  Serial.println(obj.hasOwnProperty("main"));             // (2) 0 ... OK
  Serial.println(obj["list"][0].hasOwnProperty("main"));  // (3) 1 ... OK
}

void Test_hasPropertyEqual(JSONVar &obj) {
  JSONVar London = "London";

  Serial.println("===== Test_hasPropertyEqual =====");
  Serial.println(obj.hasPropertyEqual("code", "200"));            // (4) 1 ... OK
  Serial.println(obj["city"].hasPropertyEqual("name", "London")); // (5) 1 ... OK
  Serial.println(obj["city"].hasPropertyEqual("name",  London )); // (6) 1 ... OK

  JSONVar num = 0;
//Serial.println(obj["city"].hasPropertyEqual("name", num));  // (7) Expect 0 (Q1) ... Guru Meditation Error: Core  1 panic'ed (LoadProhibited). Exception was unhandled.
//Serial.println(obj.hasPropertyEqual("message", num));       // (8) Expect 1 (Q1) ... Guru Meditation Error: Core  1 panic'ed (LoadProhibited). Exception was unhandled.
//Serial.println(obj.hasPropertyEqual("message", 0  ));       // (9) Expect 1 (Q1) ... Guru Meditation Error: Core  1 panic'ed (LoadProhibited). Exception was unhandled.
}

void Test_filter(JSONVar &obj) {
  Serial.println("===== Test_filter =====");
  Serial.println(JSON.stringify(obj.filter("code", "200")));            // (10) OK
  Serial.println(JSON.stringify(obj["city"].filter("name", "London"))); // (11) OK

  JSONVar filter;
  filter["name"] = "London";
  Serial.println(JSON.stringify(obj.filter("city", filter)));     // (12) null ... ? (Q2)

  filter = 0;
  Serial.println(JSON.stringify(obj.filter("message", filter)));  // (13) null ... ? (Q3)
  Serial.println(JSON.stringify(obj.filter("message", 0     )));  // (14) null ... ? (Q3)
}

void Test_printTo(JSONVar &obj) {
  Serial.println("===== Test_printTo =====");
  if (!SD.begin()) {
    Serial.println("SD initialization failed.");
    return;
  }

  File myFile = SD.open("/test.txt", FILE_WRITE);
  if (!myFile) {
    Serial.println("Error opening test.txt");
    return;
  }

  size_t len = obj.printTo(myFile);
  myFile.close();

  char* buf = (char*)malloc(len + 1);
  if (!buf) {
    Serial.println("malloc failed.");
    return;
  }

  myFile = SD.open("/test.txt", FILE_READ);
  len = myFile.read((uint8_t*)buf, len);
  buf[len] = '\0';

  JSONVar tmp = JSON.parse(buf);        // (15) OK
  Serial.println(JSON.stringify(tmp));
  free((void*)buf);
}

void setup() {
  Serial.begin(115200);
  while (millis() < 1500);

  Serial.println("\nStart.");

  JSONVar myObject = JSON.parse(input);
  String type = JSON.typeof(myObject);
  if (type == "undefined") {
    Serial.println("Parsing input failed.");
    return;
  }

  Test_hasOwnProperty   (myObject);
  Test_hasPropertyEqual (myObject);
  Test_filter           (myObject);
  Test_printTo          (myObject);

  Serial.println("Done.");
}

void loop() {}

Q1

(7), (8), and (9) in Test_hasPropertyEqual() are supposed to verify whether "Property" has a specific numeric value. However, the results are as stated in the comments. Is my usage incorrect?

If I modify the line 516 of JSONVar.cpp as follows, the error will not occur...

  return json != NULL && json->valuestring && strcmp(value, json->valuestring) == 0;

Q2

(12) in Test_filter() is code that expects to get the same result as (11). Is filter being used incorrectly?

Q3

(13) and (14) in Test_filter() are supposed to filter specific "key" and "value". Am I using them incorrectly?

Q4

I have a question for the Arduino team in particular: Arduino_JSON is listed as [BETA] in the library manager, but can we expect future updates?

Thank you.

Looks like that only supports comparing to JSON-strings, given the (C-style) cast

When you pass a JSON-number, the conversion function

returns NULL, so that blows up. Same applies to filter

The JSONVar has to be a plain JSON-string, not a JSON-object or number

Maybe if this gets further than v0.2.0, it will include other types.

Beware of the difference between these:

#include <ArduinoJson.h>
#include <Arduino_JSON.h>

ArduinoJson appears to be more mature. I currently use V7.x

Hi @kenb4, thank you for your detailed investigation. It seems we'll just have to hope for the next version. However, since it hasn't been updated in a few years, we may not be able to have high hopes.

For now, I'll work around this by storing values ​​as strings instead of numbers in the application I'm working on.

Also I'll consider raising an issue on Github.

Thank you again for your time.

Thank you for your suggestion, @6v6gt.

I've already tested ArduinoJson and confirmed that it seems like it will achieve my goals.

ArduinoJson is also a great library, but I prefer the simple, Javascript-like API of Arduino_JSON, so I'd like to stick with it a little longer.

I find the syntax quite OK with ArduinoJson.

It looks like you are working with the OpenWeatherMap API. Interesting because I am working on such a project now.

I used a Random Nerd tutorial to get me started although I used a different JSON library. I get a JsonDocument with up to 40 three hour slots from the API. This is how I parse selected parts of it into an array of structs for displaying. The JsonDocument is about 16kB on the heap so, with an ESP32, I've not needed to give too much attention to filtering it.

void jsonToImg(JsonDocument doc) {
  // read json doc, load jsonImg[] and part format/process
  // attempt general handling of implausible data (all nulls etc. if JSON deserialise fails)

  log_d("Entering function.");

  for (int i = 0; i < MAX_ENTRIES; i++) {

    String dt_txt = doc["list"][i]["dt_txt"];
    
    const char * icon = doc["list"][i]["weather"][0]["icon"];


    String pod = doc["list"][i]["sys"]["pod"];
    float temp = doc["list"][i]["main"]["temp"];


    // temperature
    int tempI = round(temp);
    snprintf(jsonImg[i].temp, 4, "%*d", 3, tempI);  // https://cplusplus.com/reference/cstdio/printf/

    // icon
    snprintf(jsonImg[i].iconPath, 9, "/%s.bmp", icon );

    // header date
    int dom = dt_txt.substring(8, 10).toInt();
    int mon = dt_txt.substring(5, 7).toInt();
    if ( mon > 0 ) snprintf(jsonImg[i].headerDate, 7, "%02d.%s", dom, monName[mon - 1]);

    int hr = dt_txt.substring(11, 13).toInt();
    snprintf(jsonImg[i].time, 3, "%02d", hr);

    int yr = dt_txt.substring(0, 4).toInt();
    snprintf(jsonImg[i].day, 4, "%s", dow[dayofweek(dom, mon, yr)]);

    jsonImg[i].isDay = (pod == "d");
  }
  log_d("Exiting function.\n");
}

Hello, @6v6gt

Thank you for your code.

The JSON data used in my test code was taken from the ArduinoJson example, and my application is quite different :wink:

Based on @kenb4's analysis, I start to think the filter function could be used if I stored all "values" as strings instead of using numerical values.

Still, your code is very helpful. Even without the filter function, the JSON format is known, so directly referencing the values ​​would solve my problem.

Actually, there's another reason I want Arduino_JSON to be updated. I've contacted Arduino support and am awaiting a response.

I'll defer marking this thread as "solved" until then.

I appreciate your understanding.

OK. I see. Using json for configuration information is an interesting approach and that should work well.

In the past, I've used a struct and serialised it out to an EEPROM. However, this does not work well if there are many varying length strings because you are forced to accommodate the maximum possible length for each string parameter (WLAN credentials etc.). Here JSON is clearly better.

I use the ESP32 for most projects now and use the new Preferences library there for persistent storage of configuration data and usually provide a web interface for updating it. However, you can't easily transfer that to another device using an SD card, or at least I don't think you can because there doesn't appear to be a method for exporting an entire namespace.

Hi @6v6gt, thank you for sharing your experience.

Yeah, I'll keep in mind for my future projects!

Now it's time I should explain about my current project. I'm currently working on developing MP3 Music Player on CYD.

Music files extracted from CDs are saved on the SD card by artist and album title:

I'm trying to implement a UI that allows users to select albums to add into a playlist based on their preferred classification. The following is the current mockup using LVGL:

demo

I'm considering saving this "preferred classification" as a JSON data file on the SD card, that would look something like this:

[
  {
    "name" : "ROCK",
    "path" : {
      "artist1" : [
        "album1",
        "album2"
      ],
      "artist2" : [
        "album3"
      ]
    }
  },
  {
    "name" : "JAZZ",
    "path" : {
      "artist3" : [
        {
          "1990s" : [
            "album4"
          ]
        },
        {
          "2024" : [
            "album5",
            "album6"
          ]
        }
      ]
    }
  }
]

For example, if I select "ROCK" from the drop-down list, {"name" : "ROCK"} will be filtered from the JSON data and reflected in the UI screen.

I considered using more richer JSON format, but I'm trying to keep it as compact as possible, so that the path to the music files can be obtained by traversing "path" and concatenating the directory names.

I also wanted to include an "integer value" into the JSON data to record the number of songs in the album title, but now I'm considering obtaining such information in a different way.

Anyway, although I mentioned my preference, I haven't yet decided whether "Arduino_JSON" or "ArduinoJson" is appropriate.

"ArduinoJson", as you suggested, is still one of the options.

Thank you again for your comment!