Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Array of objects #15

Open
mapicard opened this issue Jan 12, 2021 · 1 comment
Open

Array of objects #15

mapicard opened this issue Jan 12, 2021 · 1 comment

Comments

@mapicard
Copy link

Hi,
Is it possible to implement an array of objects with this library? If so, could you provide an example of implementing the following

{
  "movies": [
    { "title": "Raiders of the Lost Ark", "director": "Ridley Scott"},
    { "title": "Ghostbusters", "director": "Steven Spielberg"}
  ]
}

Thank you

@mapicard mapicard changed the title Table of objects Array of objects Jan 12, 2021
@manchoz
Copy link

manchoz commented Jun 8, 2021

Hi @mapicard,
Here is a possible implementation.

Try it on NestedJson.

#include <Arduino_JSON.h>

struct Movie {
  String title;
  String director;
};

Movie movies[] {
  { "Raiders of the Lost Ark", "Ridley Scott" },
  { "Ghostbusters", "Steven Spielberg" },
  { "THX 1138", "George Lucas" }
};

void setup()
{
  Serial.begin(9600);
  // Wait for Serial or start after 2.5 seconds
  for (auto startNow = millis() + 2500; !Serial && millis() < startNow; delay(500));

  // The JSON variable to host the JSON array for the movies
  JSONVar jsonMovies;
  
  // A simple index to iterate on while creating the JSON array
  int idx { 0 };
  
  // Iterate on movies
  for (const auto& m : movies) {
    // The JSON dictionary hosting the single movie element
    JSONVar jm;
    jm["title"] = m.title;
    jm["director"] = m.director;
    
    // Add the movie to the array
    jsonMovies[idx] = jm;
    idx++;
  }

  // The JSON variable hosting the root of the JSON
  JSONVar jsonRoot;
  // Add the movies array to the "movies" key
  jsonRoot["movies"] = jsonMovies;

  auto jsonString = JSON.stringify(jsonRoot);
  Serial.println(jsonString);
}

void loop()
{
  
}

@arduino-libraries arduino-libraries deleted a comment from rjrajbir Nov 4, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants