Write an JSON content

The first thing to do when reading or writing a JSON file/stream, is to declare the Document interface

Include ejson

#include <ejson/ejson.hpp>

Declare document interface

Write an JSON file

Write an json tree is done like:

bool retGenerate = doc.store("generate.json");

Write an JSON Stream

Writing a stream is done like this:

std::string streamOut;
bool retGenerate = doc.generate(streamOut);

Operation on Tree

Add String:

doc.add("A", ejson::String("2.5"));

Add Null:

doc.add("B", ejson::Null());

Add Number:

doc.add("C", ejson::Number(2010));

Add Boolean:

doc.add("D", ejson::Boolean(false));

Add Array with values:

ejson::Array array;
array.add(ejson::String("elem1"));
array.add(ejson::Number(22));
array.add(ejson::Null());
doc.add("E", array);

Add Object with values:

object.add("ee", ejson::String("elem1"));
object.add("55", ejson::Number(22));
object.add("lk", ejson::Null());
doc.add("F", object);

Remove a Value in an Object:

doc.remove("F");

Remove a Value in an Object:

array.remove(2);

Object concept

The ejson concept is to abstract the implementation of the internal system. All the element are mapped on shared memory. Then if you asign an element to an other, it is the same. You need to clone it if you want to have new standalone element.

ejson::Value tmpClone = doc["object F"].clone();

All example file

#include <test-debug/debug.hpp>
#include <ejson/ejson.hpp>
#include "write.hpp"
static void writeToFile() {
doc.add("A", ejson::String("2.5"));
doc.add("B", ejson::Number(2010));
doc.add("C", ejson::Boolean(false));
doc.add("D", ejson::Array());
TEST_INFO("store");
bool retGenerate = doc.store("generate.json");
TEST_INFO("parse ret = " << retGenerate);
TEST_INFO("Debug display of the tree:");
doc.display();
}
static void writeToString() {
doc.add("A", ejson::String("2.5"));
doc.add("B", ejson::Number(2010));
doc.add("C", ejson::Boolean(false));
doc.add("D", ejson::Array());
TEST_INFO("generate");
std::string streamOut;
bool retGenerate = doc.generate(streamOut);
TEST_INFO("parse ret = " << retGenerate);
TEST_INFO("Debug display of the tree:");
doc.display();
}
static void writeAll() {
doc.add("A", ejson::String("2.5"));
doc.add("B", ejson::Null());
doc.add("C", ejson::Number(2010));
doc.add("D", ejson::Boolean(false));
ejson::Array array;
array.add(ejson::String("elem1"));
array.add(ejson::Number(22));
array.add(ejson::Null());
doc.add("E", array);
ejson::Object object;
object.add("ee", ejson::String("elem1"));
object.add("55", ejson::Number(22));
object.add("lk", ejson::Null());
doc.add("F", object);
// remove the object named "F"
doc.remove("F");
// Remove element 2 in the array
array.remove(2);
doc.display();
}
void appl::write() {
writeToFile();
writeToString();
writeAll();
}