Hi, I need to convert all my XML generation code to JSON as the target no longer accepts XML.

I’m looking at the documentation for the var class but can’t really get my head around how to create and populate objects.

Anyone got any pointers? thx

There is no ready made solution, because there are features of JSON, that cannot be mapped to XML (arrays).
But actually the direction you are after shouldn’t be a problem.

Shouldn’t be hard to write

1 Like

You’ll have to go via the DynamicObject class to build a json structure since json (JavaScript Object Notation) is a way of expressing JavaScript objects serialised to strings and if I get it right, the purpose of the DynamicObject class is to express such objects. After putting all those nested dynamic object instances together you can finally wrap them into a var.

While this is okay for generating small pieces json data this way, I prefer using https://github.com/nlohmann/json for more complex json applications since it’s really straightforward to use, well documented and header only :slight_smile:


XML isn’t property-based like JSON is, and doesn’t have constructs like it so you’re in for a bit (a lot?) of pain. You’ll have to have your own solution.

That being said, you could take the approach of taking nested/child XML objects and converting them into JSON arrays of objects (ie:a combination of juce::Array<juce::var>, where each array element is a juce::DynamicObject, primitive type, or juce::String).

And if you consider XML attributes as JSON properties, it’ll get you most of the way there.

To be fair, I’ve actually had amazing luck with this approach myself, especially in combination with a juce::ValueTree

hi - thanks for the replies.

The XML is not complex so using the approach of DynamicObjects for each XML node will be fine.

I’m trying to mix Juce::Arrayjuce::var and juce::DynamicObjects with no real luck.
Does this code look correct to create an array of objects?
When i write the file to json, Devices is always empty, whatever I add into it.

Array<var> array;

for ( auto p_device : device_list ) {
    if ( p_device->is_customised() ) {
        auto *p_object = new DynamicObject();
        p_device->store( *p_object );
        array.add( var( p_object ) );

object.setProperty( "Devices", array );
1 Like

+1 for nlohmann.
The only rough edge I’ve found is it’s use of exceptions which is just something different to the way JUCE normally works rather than an actual problem.

1 Like

I think that can be turned off now.


Overall it looks ok. One thing I don’t have is enough context here to understand what store is doing.

In situations like this, it’s a good thing to do a rough draft JSON to know what you want/expect. Might be worth sharing that here alongside what you’re getting, so as to compare? PM me if you can’t share data publicly.