Skip to content

Create a json array


Example on how to create an array consisting of other jsons, like this:

Will create json:
[
    {
        "name": "Ethel Cline",
        "age": 33
    },
    {
        "name": "Rayhaan Newton",
        "age": 60
    },
    {
        "name": "Elicia Goff",
        "age": 17
    },
    {
        "name": "Neil Dominguez",
        "age": 69
    },
    {
        "name": "Martyn Nunez",
        "age": 42
    }
]
Setup (C++):
// First, we need some data to put into the array.
// This is nothing but an example and has absolutely nothing to do with JasonPP.
struct Person
{
    std::string name;
    int age;
};

void Setup()
{
    std::vector<Person> persons;
    persons.push_back({ "Ethel Cline",    33 });
    persons.push_back({ "Rayhaan Newton", 60 });
    persons.push_back({ "Elicia Goff",    17 });
    persons.push_back({ "Neil Dominguez", 69 });
    persons.push_back({ "Martyn Nunez",   42 });
    // ...
}
Procedural (C++):
Json json = JsonData(JSON_DATA_TYPE::ARRAY); // Create empty JsonData of type ARRAY

// Perform for each person
for (unsigned int i = 0; i < persons.size(); i++)
{
    // Create a new JsonBlock object
    JsonBlock personInfo;
    personInfo.Add("name").SetStringData(persons[i].name);
    personInfo.Add("age").SetIntData(persons[i].age);

    // Add that json object to our main array
    json.AsArray.Add(personInfo);
}

std::cout << json.Render() << std::endl;
Inline (C++):
Json json = JsonData(JsonArray({
    JsonData(JsonBlock({
        Ele("name", "Ethel Cline"),
        Ele("age", 33),
    })),
    JsonData(JsonBlock({
        Ele("name", "Rayhaan Newton"),
        Ele("age", 60),
    })),
    JsonData(JsonBlock({
        Ele("name", "Elicia Goff"),
        Ele("age", 17),
    })),
    JsonData(JsonBlock({
        Ele("name", "Neil Dominguez"),
        Ele("age", 69),
    })),
    JsonData(JsonBlock({
        Ele("name", "Martyn Nunez"),
        Ele("age", 42),
    }))
}));

std::cout << json.Render() << std::endl;