Construct var programmatically and convert to JSON

Just replying as a more ‘notes to myself’ about this:

I really like this function, especially when it’s treated as a lambda.
I think the hardest part about creating JSON programmatically is translating, if you know what you want the final tree to look like, the final tree into code.

Say I have a tree that I want to look like this:

{
    "id1": "value",
    "id2": "value",
    "id3": 
    {
        "id5": "value",
        "id6": "value"
    },
    "id4": 
    [
        {
            "id7": "value",
            "id8": "value"
        },
        {
            "id9": "value",
            "id0": "value"
        }
    ]
}

So, what does that look like programmatically? you gotta work your way from the inside out:

        {
            "id9": "value",
            "id0": "value"
        }

Using pneyrink’s function as a lambda:

auto JSONHelper =
    [](juce::var& object, juce::String key, juce::var value ){
        if( object.isObject() ) {
            object.getDynamicObject()->setProperty(key, value);
        }
    };

we can create the above JSON object simply:

var newObj90( new DynamicObject() );
JSONHelper( newObj90, "id9", "value" );
JSONHelper( newObj90, "id0", "value" );

So, let’s make that a lambda as well:

auto nestedObject = [JSONHelper](const String& id1, const String& val1, const String& id2, const String& val2, ) {
    var newObj( new DynamicObject() );
    JSONHelper( newObj, id1, val1 );
    JSONHelper( newObj, id2, val2 );
    return newObj;
}

if we have an array of these newObj’s, then that’s easy too:

var newArrayObj( new DynamicObject() );
JSONHelper( newArrayObj, "id4", Array<var>() );

and now just push those nested JSON objects into the array:

if( auto id4 = tree.getProperty("id4", var()).getArray() ) {
    id4->addIfNotAlreadyThere( nestedObject("id9", "value", "id0", "value") );
    id4->addIfNotAlreadyThere( nestedObject("id7", "value", "id8", "value") );
}

You can start to see that the tree’s structure looks like this, programmatically:

var tree( new DynamicObject() );
{
     JSONHelper( tree, "id1", "value" );
     JSONHelper( tree, "id2", "value" );
     JSONHelper( tree, "id3", nestedObject("id5", "value", "id6", "value" ) );
     JSONHelper( tree, "id4", Array<var>() );
     tree.getProperty("id4", var()).getArray()->addIfNotAlreadyThere( nestedObject("id9", "value", "id0", "value") );
     tree.getProperty("id4", var()).getArray()->addIfNotAlreadyThere( nestedObject("id7", "value", "id8", "value") );
}

you could take this a step further, modify nestedObject() such that it takes 2 arrays of vars, one for keys, and one for values. just make sure they’re the same size and loop thru them to populate the DynamicObject that’ll get placed in the node.

4 Likes