Quick & Dirty JSON to ValueTree Parser

I was just recently working on assembling JSON data from HTTP responses, and trying to work that into ValueTree instances to drive my app. It’s not a lot of effort so figure to share.

The code has the aesthetic value of horse manure but hopefully you can also make use of it and improve upon it.

namespace
{
    const Identifier rootId = "root";
    const Identifier propertyId = "property";

    inline void setProperty (ValueTree& source, const Identifier& id, const var& v)
    {
        jassert (id.isValid() && ! v.isVoid());
        source.setProperty(id, v, nullptr);
    }

    inline void appendValueTree(ValueTree& parent, const Identifier& id, const var& v)
    {
        if (! parent.isValid() || id.isNull() || v.isVoid())
            return;

        if (auto* ar = v.getArray())
        {
            for (const auto& item : *ar)
            {
                ValueTree child(rootId);
                parent.appendChild(child, nullptr);
                appendValueTree(child, propertyId, item);
            }

            return;
        }

        if (auto* object = v.getDynamicObject())
        {
            ValueTree child(id);
            parent.appendChild(child, nullptr);

            for (const auto& prop: object->getProperties())
                appendValueTree(parent, prop.name, prop.value);

            return;
        }

        ValueTree child(id);
        parent.appendChild(child, nullptr);
        setProperty(child, Identifier(String("property") + String(parent.getNumProperties())), v);
    }

    inline ValueTree createValueTreeFromJSON(const var& json)
    {
        if (json.isVoid())
            return {};

        ValueTree root(rootId);
        appendValueTree(root, rootId, json);
        return root;
    }

    inline ValueTree createValueTreeFromJSON(const String& data)
    {
        return createValueTreeFromJSON(JSON::parse(data));
    }
}
7 Likes

Did you happen to have a ValueTree-to-JSON companion for this?

edit, nevermind found somethin’ from @FigBug!

1 Like