JSON
JSON is a text format for objects, arrays, strings, numbers, booleans, and null. C++ has no standard JSON type. nlohmann/json is the usual convenience library; RapidJSON and simdjson are the usual speed libraries.
Detailed Explanation
You send {"id":42,"status":"SHIPPED"} over HTTP. The bytes are UTF-8 text. A library parses them into a DOM (a tree you index) or SAX-streams them (callbacks per key). nlohmann's json is a DOM that feels like operator[]. RapidJSON is a DOM you control the allocator of. simdjson is a from-chars-speed parser that produces a document view.
nlohmann:
auto j = nlohmann::json::parse(body);
int id = j.at("id").get<int>();
at throws if the key is missing or the type is wrong. operator[] inserts a null on a missing key if j is not const — that is a mutation trap on a parse result you thought was read-only. Use at or contains for input.
Numbers: JSON has one number type. nlohmann will store an integer if it fits, else a float. get<int>() on 1e20 throws or overflows depending on the value. Money should be a string or an integer count of cents, not a JSON float.
Strings are UTF-8. std::string holds the bytes. Do not assume size() is characters. Escapes (\n, \u0041) are decoded by the parser.
Serialise with j.dump(). dump(2) pretty-prints. Do not build JSON by concatenating strings; you will forget to escape a quote and open an injection hole next to HTML or SQL.
Schema: C++ does not check a schema unless you write it. Validate required keys and ranges after parse. For public APIs, reject unknown required types with 400, not a default 0.
Performance: nlohmann is fine until profiles say otherwise. simdjson plus a tight struct is the next step. Do not parse a 100 MB body on the request thread without a size cap.
nlohmann::json can get<User>() if you define to_json/from_json. That is the usual mapping to structs. Keep those functions next to the type.
Code Examples
#include <nlohmann/json.hpp>
#include <iostream>
#include <string>
int main() {
std::string body = R"({"id":42,"status":"SHIPPED"})";
auto j = nlohmann::json::parse(body);
std::cout << j.at("id").get<int>() << '\n'; // prints: 42
std::cout << j.at("status").get<std::string>() << '\n'; // prints: SHIPPED
std::cout << j.dump() << '\n';
}#include <nlohmann/json.hpp>
struct Order { int id; std::string status; };
void to_json(nlohmann::json& j, const Order& o) {
j = {{"id", o.id}, {"status", o.status}};
}
int main() {
nlohmann::json j = Order{1, "NEW"};
return j.at("id") == 1 ? 0 : 1;
}Common Gotchas
`j["key"]` on a non-const parse tree inserts null
a typo creates a field. Use `at` or `const json`.
Floating-point money
`19.99` is not a decimal. Use integer cents.
Building JSON with `string` plus `+`
a user name with `"` breaks the document. Use the library's dump.
Parse exceptions
`parse` throws `json::parse_error`. Catch at the HTTP boundary.