ValueTree <=> JSON

If anyone needs a simple ValueTree <=> JSON conversion, here’s one:


#pragma once
#include "JuceHeader.h"
juce::String valueTreeToJsonString (const juce::ValueTree&, const int numDecimalPlaces = 3, const int indent = 4);
juce::ValueTree valueTreeFromJsonString (const juce::String&, juce::Identifier);


#include "ValueTreeJson.h"

using namespace juce;

static DynamicObject::Ptr valueTreeToJsonObj (const ValueTree& tree)
    DynamicObject::Ptr result {new DynamicObject};
    for (int i = 0; i < tree.getNumProperties(); ++i)
        const auto name = tree.getPropertyName (i);
        result->setProperty (name, tree.getProperty (name));
    for (int i = 0; i < tree.getNumChildren(); ++i)
        const auto child = tree.getChild (i);
        result->setProperty (child.getType(), var (valueTreeToJsonObj (child)));
    return result;

String valueTreeToJsonString (const ValueTree& tree, const int numDecimalPlaces, const int indent)
    MemoryOutputStream stream;
    valueTreeToJsonObj (tree)->writeAsJSON (stream, indent, false, numDecimalPlaces);
    return stream.getMemoryBlock().toString();

static ValueTree valueTreeFromJsonObj (DynamicObject* src, Identifier ident)
    ValueTree result (ident);
    for (auto& p : src->getProperties())
        if (auto* obj = p.value.getDynamicObject(); obj != nullptr)
            result.appendChild (valueTreeFromJsonObj (obj,, nullptr);
            result.setProperty (, p.value, nullptr);
    return result;

ValueTree valueTreeFromJsonString (const String& src, Identifier ident)
    auto parsed = JSON::parse (src);
    auto dynObj = parsed.getDynamicObject();
    if (dynObj == nullptr)
        return {};
    return valueTreeFromJsonObj (dynObj, ident);

Cheers, and if I missed that this already exists in some JUCE method let me know :slight_smile:

Similar threads: Convert ValueTree to DynamicObject? - #10 by cpr2323 Json to valuetree parser



For all those who have compile problems like this:

No matching conversion for functional-style cast from 'DynamicObject::Ptr' (aka 'ReferenceCountedObjectPtr<DynamicObject>') to 'var'

The reason is that JUCE_STRICT_REFCOUNTEDPOINTER (juce core module option) is activated.
It was quite tricky to find the reason.