![]() |
simdjson 4.6.4
Ridiculously Fast JSON
|
In some instances, you may want to configure your software at compile-time with a JSON document. Maybe you have a single code base but many different possible configurations, all resulting in different software. For example, you might be programming robots, using the same software, but different robot configurations.
To achieve the desired result, you have a few options. You may start the software and parser a JSON file at runtime. Or you might convert your JSON data into C++ code that you can compile with your software.
With C++26, there is another way: parse the JSON file along with your C++ code. In this manner, the JSON data becomes native C++ data.
The simdjson library supports parsing JSON documents at compile time if you have C++26 support. To activate C++26 reflection support, you can compile your code with the SIMDJSON_STATIC_REFLECTION macro set:
The simdjson::compile_time::parse_json function parses a JSON document at compile time and returns a constexpr structure reflecting its content. We support the full range of JSON values, which are mapped to C++ types as in the following table.
| JSON type | C++ type |
|---|---|
| object | anonymous struct |
| array | std::array<T, N> (homogeneous) |
| string | const char* (UTF-8) |
| number | int64_t, uint64_t, double |
true/false | bool |
null | std::nullptr_t |
Suppose you want to parse the following JSON document:
Reminder: In C++, R"( )" allows us to write multi-line strings with unescaped quotes.
You can do so, at compile-time, as follows:
You can nest objects and arrays:
Top-level arrays are allowed:
Given that the parsed data is made of structures that depend on the JSON input, you might want to check that it conforms to your expectation. You can do so with concepts.
Let us consider this example:
You might want to ensure that the result is an array of persons. You can define your expectation with concepts like so:
And then a simple static assert with decltype is sufficient to check that the expectation is met:
In practice, you may have a JSON file, say json_data that you want to parse at compile time. You may do so as follows.
We have a few limitations which trigger compile-time errors if violated.
const char* in UTF-8, but they must not contain embedded nulls. We would prefer to represent them as std::string or std::string_view, and hope to do so in the future.These limitations are safe in the sense that they result in compile-time errors. Thus you will not get truncated strings or imprecise floats silently.
Although we are committed to maintaining the functionality in the long run, the compile_time::parse_json function is subject to change.