json README

The project's README from github.com/nlohmann/json. As one markdown file: README.md.

JSON for Modern C++

Build Status Ubuntu macOS Windows Coverage Status Coverity Scan Build Status Codacy Badge Cirrus CI Fuzzing Status Try online Documentation GitHub license GitHub Releases Packaging status GitHub Downloads GitHub Issues Average time to resolve an issue CII Best Practices OpenSSF Scorecard Backup Status GitHub Sponsors REUSE status Discord

Design goals

There are myriads of JSON libraries out there, and each may even have its reason to exist. Our class had these design goals:

Other aspects were not so important to us:

See the contribution guidelines for more information.

Sponsors

You can sponsor this library at GitHub Sponsors.

:raising_hand: Priority Sponsor

:label: Named Sponsors

Further support

The development of the library is further supported by JetBrains by providing free access to their IDE tools.

JetBrains logo.

Thanks everyone!

Support

:question: If you have a question, please check if it is already answered in the FAQ or the Q&A section. If not, please ask a new question there.

:books: If you want to learn more about how to use the library, check out the rest of the README, have a look at code examples, or browse through the help pages.

:construction: If you want to understand the API better, check out the API Reference or have a look at the quick reference below.

:bug: If you found a bug, please check the FAQ if it is a known issue or the result of a design decision. Please also have a look at the issue list before you create a new issue. Please provide as much information as possible to help us understand and reproduce your issue.

There is also a docset for the documentation browsers Dash, Velocity, and Zeal that contains the full documentation as an offline resource.

Quick reference

Full API documentation

Examples

Here are some examples to give you an idea how to use the class.

Besides the examples below, you may want to:

→ Check the documentation
→ Browse the standalone example files
→ Read the full API Documentation with self-contained examples for every function

Read JSON from a file

The json class provides an API for manipulating a JSON value. To create a json object by reading a JSON file:

#include <fstream>
#include <nlohmann/json.hpp>
using json = nlohmann::json;

// ...

std::ifstream f("example.json");
json data = json::parse(f);

If using modules (enabled with NLOHMANN_JSON_BUILD_MODULES), this example becomes:

import std;
import nlohmann.json;

using json = nlohmann::json;

// ...

std::ifstream f("example.json");
json data = json::parse(f);

Creating json objects from JSON literals

Assume you want to hard-code this literal JSON value as a json object:

{
  "pi": 3.141,
  "happy": true
}

There are various options:

// Using (raw) string literals and json::parse
json ex1 = json::parse(R"(
  {
    "pi": 3.141,
    "happy": true
  }
)");

// Using user-defined (raw) string literals
using namespace nlohmann::literals;
json ex2 = R"(
  {
    "pi": 3.141,
    "happy": true
  }
)"_json;

// Using initializer lists
json ex3 = {
  {"happy", true},
  {"pi", 3.141},
};

JSON as a first-class data type

Here are some examples to give you an idea how to use the class.

Assume you want to create the JSON object

{
  "pi": 3.141,
  "happy": true,
  "name": "Niels",
  "nothing": null,
  "answer": {
    "everything": 42
  },
  "list": [1, 0, 2],
  "object": {
    "currency": "USD",
    "value": 42.99
  }
}

With this library, you could write:

// create an empty structure (null)
json j;

// add a number stored as double (note the implicit conversion of j to an object)
j["pi"] = 3.141;

// add a Boolean stored as bool
j["happy"] = true;

// add a string stored as std::string
j["name"] = "Niels";

// add another null object by passing nullptr
j["nothing"] = nullptr;

// add an object inside the object
j["answer"]["everything"] = 42;

// add an array stored as std::vector (using an initializer list)
j["list"] = { 1, 0, 2 };

// add another object (using an initializer list of pairs)
j["object"] = { {"currency", "USD"}, {"value", 42.99} };

// instead, you could also write (which looks very similar to the JSON above)
json j2 = {
  {"pi", 3.141},
  {"happy", true},
  {"name", "Niels"},
  {"nothing", nullptr},
  {"answer", {
    {"everything", 42}
  }},
  {"list", {1, 0, 2}},
  {"object", {
    {"currency", "USD"},
    {"value", 42.99}
  }}
};

Note that in all these cases, you never need to "tell" the compiler which JSON value type you want to use. If you want to be explicit or express some edge cases, the functions json::array() and json::object() will help:

// a way to express the empty array []
json empty_array_explicit = json::array();

// ways to express the empty object {}
json empty_object_implicit = json({});
json empty_object_explicit = json::object();

// a way to express an _array_ of key/value pairs [["currency", "USD"], ["value", 42.99]]
json array_not_object = json::array({ {"currency", "USD"}, {"value", 42.99} });

Serialization / Deserialization

To/from strings

You can create a JSON value (deserialization) by appending _json to a string literal:

// create object from string literal
json j = "{ \"happy\": true, \"pi\": 3

json (nlohmann/json)

Searching Database…

50.8K ·GitHub
Что это такое?Библиотека JSON для современного C++ (nlohmann/json), которая позволяет читать, создавать и изменять значения JSON с понятным синтаксисом в стиле STL прямо в коде на C++.
Это фреймворк или просто библиотека, которую я подключаю?Это одна библиотека только из заголовочных файлов: вся реализация находится в одном файле json.hpp, и никакой отдельной сборки или подпроекта не требуется.
Как мне добавить её в проект?Просто положите json.hpp в свой проект и подключите его через #include, либо подключите через CMake, менеджер пакетов (vcpkg, Conan и др.) или Pkg-config; также она доступна как модули C++20 через опцию NLOHMANN_JSON_BUILD_MODULES.
Нужны ли мне внешние зависимости или особые флаги компилятора?Внешние зависимости не требуются; библиотека написана на чистом C++11 и должна работать с настройками компилятора по умолчанию.
Это самая быстрая библиотека JSON?Нет: авторы сознательно поставили удобство интеграции выше скорости и эффективности использования памяти, поэтому другие библиотеки JSON могут её обогнать.
Какие стандарты и форматы, связанные с JSON, поддерживаются помимо обычного JSON?Поддерживаются JSON Pointer (RFC 6901) и JSON Patch (RFC 6902) для адресации, сравнения и изменения документов, JSON Merge Patch, а также бинарные форматы BSON, CBOR, MessagePack, UBJSON и BJData для компактной сериализации.
Можно ли мне автоматически преобразовывать свои классы C++ в JSON и обратно?Да, библиотека поддерживает неявные преобразования в пользовательские типы и из них, включая специализацию преобразований для перечислений (enum), через механизм «Conversions to/from arbitrary types».
Насколько хорошо протестирована эта библиотека?Заявлено покрытие кода 100 % и обширное модульное тестирование; библиотека проверена на утечки памяти с помощью Valgrind и Clang Sanitizers и постоянно тестируется фаззингом в Google OSS-Fuzz.
Можно ли мне использовать контейнеры STL, например std::vector или std::map, напрямую для построения JSON?Да, библиотека умеет напрямую преобразовывать контейнеры STL, и если вы уже умеете пользоваться std::vector или std::map, то вы уже знаете большую часть нужного API.
Creator
nlohmann
Size
304.9 MB
Stars
50.8K
Age
13y
Commits · 90 Days