json files problems

Hello everybody. I need some help, let me explain:

I have a .json file saved in SPIFFS, it contains this type of data:

{"-AABBCC123":{"name":"Clark","number":"85625"},"-EEFFGG456":{"name":"Kate","number":"87963"}}

When I deserialize this file, I can print the value of the field for a specific person, like this:

void test()
{
  File file = SPIFFS.open("/names.json", "r");

  deserializeJson(doc, file);

  const char* doc1 = doc["-AABBCC123"]["number"];
  Serial.println((char*)doc1);
  file.close();
}

Then, on the serial monitor, the value “85625” is shown.
So, I need to do a check to see if a given field in the entire table is equal to a given value, something like this:

for(int i=0; i<4; i++)
{
  if(doc[i]["number"] == "1234")
   {
             ....
   }
}

But I don’t know how I can do that, I don’t know how to make this comparison by checking a field for each person in the table. I am newbie to ESP32 and know very little about json on Arduino. Can anyone give me any tips, any light, for me to accomplish this?
Thank you from the heart.

somebody?

I'm not familiar with ArduinoJson library, but maybe this can help :

And, instead of ==, you have to use function strcmp to compare two strings

Thanks, it worked like this:

File file = SPIFFS.open("/names.json", "r");
  deserializeJson(doc, file);
  JsonObject root = doc.as<JsonObject>();

  for (JsonPair kv : root)
  {
    Serial.println(kv.key().c_str());
    if (doc[kv.key().c_str()]["number"] == "85625")
    {
      Serial.println("found");
    }
  }

Thanks again :slight_smile:

NP :slight_smile:

It's a good idea to break the for loop when the number is found, to avoid uneccessary work.

And possibly a smarter idea would be to have another json file containing the "inverted" data, where the key is the number and value is the "id", for example:

{"85625":"-AABBCC123"}

Or a single file containing all the data

{
  "ids":
  {
    "-AABBCC123":
    {
      "name":"Clark",
      "number":"85625"
    },
    "-EEFFGG456":
    {
      "name":"Kate",
      "number":"87963"
    }
  },
  "numbers":
  {
    "85625":
    {
      "name":"Clark",
      "id":"-AABBCC123"
    },
    "87963":
    {
      "name":"Kate",
      "id":"-EEFFGG456"
    }
  }
}

So you wouldn't need a for loop to retrieve the "id"

This topic was automatically closed 120 days after the last reply. New replies are no longer allowed.