Log in

View Full Version : Using JSON (nlohmann::json) to simplify AVS array handling in C++


wonkey_monkey
30th April 2026, 23:14
AVS arrays are great and more people should use them. That's what I think, anyway.

But they can be a pain.

Suppose you have a C++ filter and you want the user to provide an array of floats in their call, e.g.:

clip.MyFilter([ 1.0, 2.3, 3.14159 ])

To make sure the user has passed a valid array, you'll need to test each element to confirm it IsFloat(). And things get more complicated if the plugin expects more complicated arrays, such as an array of arrays containing pairs of floats:

clip.MyFilter([ [ 1.0, 2.3 ], [ 3.14159, 32.8 ] ])

Now you have to check that each element of the top array is an array, and that each of them contains two floats only.

I found what I think is quite a neat way of simplifying this process by converting the passed array to, and from, a JSON object, in this case using the nlohmann::json (https://github.com/nlohmann/json/releases) library.

All you need from it is the json.hpp file, and a helper function so that it can import AVS values:

#include "json.hpp"

void to_json(nlohmann::json& j, const AVSValue& s) {
switch (s.GetType()) {
case 'b': j = s.AsBool(); break;
case 'i': j = s.AsInt(); break;
case 'l': j = s.AsLong(); break;
case 'f': j = s.AsFloatf(); break;
case 'd': j = s.AsFloat(); break;
case 's': j = s.AsString(); break;
case 'a': {
j = nlohmann::json::array();
for (int i = 0; i < s.ArraySize(); ++i) {
j.push_back(s[i]);
}
} break;
default: throw std::runtime_error("Unhandled AVSValue type");
}
}

Then in your plugin instance creation function (or wherever), you can do something like this:

AVSValue __cdecl Create_MyFilter(AVSValue args, void* user_data, IScriptEnvironment* env) {
...
try {
nlohmann::json j = args[1];
std::vector<std::pair<float,float>> nums = j.get<std::vector<std::pair<float,float>>>();
return new MyFilter(
args[0].AsClip(),
nums
);
} catch {
... // an exception gets thrown if the array can't be parsed into a JSON object, or the JSON object can't be converted to the specified type, in this case std::vector<std::pair<float,float>>
}
}

Just thought this might come in handy for someone.