bblanchon / ArduinoJson

📟 JSON library for Arduino and embedded C++. Simple and efficient.
https://arduinojson.org
MIT License
6.63k stars 1.1k forks source link

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

Closed Sourab1801 closed 1 month ago

Sourab1801 commented 2 months ago

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 commented 2 months ago

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