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

How do i create JSON array of objects using ArduinoJson library. #2085

Open
Sourab1801 opened this issue May 2, 2024 · 1 comment
Open
Labels
question v6 ArduinoJson 6

Comments

@Sourab1801
Copy link

hello, actually I have string data like [{"time":1712751959000,"part_no":"Pno-1234","mc_status":2,"Alarm_1":0,"A1":0,"A2":0,"A3":0,"A4":0},{"dvc_id":"c4dee2e95a70","typ":"data"}] & I want to attach all this string data into a element of array. also i am getting this data continuously from machine & I want to store it into an array, I tried various options but it didn't worked for me, So can you tell this is possible or if it is possible then what is the accurate way to do that using this library. Also I am providing the code how I am adding data into array & storing it into JSON file.

MQ_Str contains above string data.

code:

**void writeJsonToFile(const char *MQ_Str) 
{

  DynamicJsonDocument jsonDoc(2048);

  // Parse the JSON string from the data stream
  DeserializationError err = deserializeJson(jsonDoc, MQ_Str);

  // Check if parsing was successful
 if (err) {
  Serial.print(F("deserializeJson() failed with code "));
  Serial.println(err.c_str());
}  

  // Create a JSON array to store the data objects
  JsonArray jsonArray = jsonDoc.createNestedArray("data");

  // Loop through each data object in the string
  for (JsonVariant data : jsonDoc.as<JsonArray>()) {
    // Add the data object to the JSON array
    jsonArray.add(data);
  }

  // Open a file for writing in JSON format
  File jsonFile = SPIFFS.open(path4, FILE_WRITE);
  if (!jsonFile) {
    Serial.println(F("Failed to open data.json for writing"));
    return;
  }

  // Serialize the JSON array to a string and write it to the file
  serializeJson(jsonArray, jsonFile);
  jsonFile.close();

  Serial.println(F("Data successfully written to data.json")); 
}``
```**
@bblanchon
Copy link
Owner

Hi,

This program mostly appends a string to a file; you don't need a JSON library for that.
Using JSONL instead of JSON for the file format would make this task trivial:

File file = SPIFFS.open(path4, FILE_WRITE);
file.println(MQ_Str);
file.close();

Best regards,
Benoit

@bblanchon bblanchon added the v6 ArduinoJson 6 label May 3, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
question v6 ArduinoJson 6
Projects
None yet
Development

No branches or pull requests

2 participants