Code generator tool
JSON to C++ Structs
Paste a JSON object or array and get C++17 structs: std::string, std::vector, std::optional for nulls and missing keys, and every struct declared before the structs that use it. It runs in your browser, so your JSON never leaves your machine.
// Paste JSON on the left (or click 'Load Sample') to generate C++ structs.What the converter generates
Here's an order with a nested customer, a list of items and a coupon that's null:
{
"orderId": 1042,
"customer": { "name": "Ada", "country": "GB" },
"items": [
{ "sku": "KB-01", "price": 49.5, "qty": 1 },
{ "sku": "MS-02", "price": 19, "qty": 2, "giftWrap": true }
],
"couponCode": null
}With the root name set to Order, the C++ tab produces:
#include <cstdint>
#include <optional>
#include <string>
#include <vector>
#include <nlohmann/json.hpp>
struct Customer {
std::string name;
std::string country;
};
struct Item {
std::string sku;
double price;
std::int64_t qty;
std::optional<bool> gift_wrap;
};
struct Order {
std::int64_t order_id;
Customer customer;
std::vector<Item> items;
std::optional<nlohmann::json> coupon_code;
};- Structs come in dependency order.
CustomerandItemare declared beforeOrder, because C++ needs a complete type before it can be a member. - Member names use snake_case:
orderIdbecomesorder_id. Names that clash with C++ keywords get a trailing underscore, so alongkey (as in longitude) becomeslong_. - Whole numbers are
std::int64_t, which holds IDs and timestamps too big for a 32-bitint. Fractions aredouble. - Missing keys and nulls are
std::optional.giftWrapis missing from one item, so it'sstd::optional<bool>.std::optionalneeds C++17. - Values with no clear type use
nlohmann::json, like the always-nullcouponCode, and the converter adds the#includefor it.
How JSON types map to C++
| JSON value | C++ |
|---|---|
| string | std::string |
| whole number | std::int64_t |
| number with a fraction, or a mix of both | double |
true or false | bool |
null, or a key some objects lack | std::optional<T> |
| array | std::vector<T> |
| object | its own struct |
mixed types, or only null | nlohmann::json |
Parse JSON into the structs with nlohmann/json
The structs are plain data, so you choose the JSON library. With the header-only nlohmann/json library, write a from_json function next to each struct. get<Order>() finds them through argument-dependent lookup and fills nested structs and vectors for you:
#include <iostream>
#include <nlohmann/json.hpp>
#include "models.hpp"
using nlohmann::json;
void from_json(const json& j, Customer& c) {
j.at("name").get_to(c.name);
j.at("country").get_to(c.country);
}
void from_json(const json& j, Item& item) {
j.at("sku").get_to(item.sku);
j.at("price").get_to(item.price);
j.at("qty").get_to(item.qty);
if (j.contains("giftWrap")) item.gift_wrap = j.at("giftWrap").get<bool>();
}
void from_json(const json& j, Order& order) {
j.at("orderId").get_to(order.order_id);
j.at("customer").get_to(order.customer);
j.at("items").get_to(order.items);
if (!j.at("couponCode").is_null()) order.coupon_code = j.at("couponCode");
}
int main() {
auto order = json::parse(R"({
"orderId": 1042,
"customer": { "name": "Ada", "country": "GB" },
"items": [{ "sku": "KB-01", "price": 49.5, "qty": 1 }],
"couponCode": null
})").get<Order>();
std::cout << order.customer.name << " ordered " << order.items.size() << " item(s)\n";
}Build it with -std=c++17 or newer, with nlohmann/json on your include path (from vcpkg, Conan or your system's package manager).
Handling bad input
j.at("key") throws when a key is missing, and get_to throws when a value has the wrong type. The messages look like this:
[json.exception.out_of_range.403] key 'country' not found
[json.exception.type_error.302] type must be number, but is stringBoth derive from nlohmann::json::exception, so one try / catch around parsing covers input you don't control.
Let a macro write the functions
When a struct's JSON keys match its member names exactly, one line writes both to_json and from_json:
NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE(Customer, name, country)Here that only works for Customer. The other structs have camelCase keys such as orderId and giftWrap, so they need the hand-written functions above.
Brushing up on C++? The C++ Classes lesson covers member functions and how a struct differs from a class, and Getting started with modern C++ covers auto, smart pointers and move semantics.
Convert JSON to other languages
The converter above has a tab for each language. These pages explain the output for the other two: