{"id":19938442,"url":"https://github.com/hunyadi/json-persistence","last_synced_at":"2025-03-01T12:43:52.192Z","repository":{"id":62361401,"uuid":"548940047","full_name":"hunyadi/json-persistence","owner":"hunyadi","description":"Type-safe JSON serialization and deserialization for C++17 and later","archived":false,"fork":false,"pushed_at":"2023-04-30T15:40:43.000Z","size":315,"stargazers_count":2,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"master","last_synced_at":"2025-01-12T04:05:30.727Z","etag":null,"topics":["cpp17","cpp20","header-only","json","json-parser","json-schema","serialization"],"latest_commit_sha":null,"homepage":"","language":"C++","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/hunyadi.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2022-10-10T12:27:43.000Z","updated_at":"2024-01-12T18:40:58.000Z","dependencies_parsed_at":"2022-10-31T13:45:59.023Z","dependency_job_id":null,"html_url":"https://github.com/hunyadi/json-persistence","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/hunyadi%2Fjson-persistence","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/hunyadi%2Fjson-persistence/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/hunyadi%2Fjson-persistence/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/hunyadi%2Fjson-persistence/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/hunyadi","download_url":"https://codeload.github.com/hunyadi/json-persistence/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":241367949,"owners_count":19951444,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["cpp17","cpp20","header-only","json","json-parser","json-schema","serialization"],"created_at":"2024-11-12T23:40:10.338Z","updated_at":"2025-03-01T12:43:52.149Z","avatar_url":"https://github.com/hunyadi.png","language":"C++","readme":"# Type-safe JSON persistence for C++17 and later\n\nThis header-only library for C++17 and later provides type-safe serialization of C++ objects into JSON strings, and deserialization of JSON strings to C++ objects.\n\n## Features\n\n* Header-only.\n* Compile-time correctness.\n* (De-)serialize fundamental types `bool`, `short`, `int`, `long`, `float`, `double`, etc. to/from their respective JSON type.\n* (De-)serialize `time_point\u003csystem_clock\u003e` type to/from an ISO 8601 date-time string in time zone UTC.\n* (De-)serialize `year_month_day` type to/from an ISO 8601 date string (C++20 and later only).\n* (De-)serialize enumeration types as their underlying integer type or as string (with auxiliary helper functions `to_string` and `from_string`).\n* (De-)serialize `vector\u003cstd::byte\u003e` type to/from a Base64-encoded string.\n* (De-)serialize heterogeneous `pair\u003cT1,T2\u003e` and `tuple\u003cT...\u003e` to/from a JSON array.\n* (De-)serialize container types `vector\u003cT\u003e`, `array\u003cT, N\u003e`, `set\u003cT\u003e`, etc. to/from a JSON array.\n* (De-)serialize dictionary types `map\u003cstring, T\u003e` and `unordered_map\u003cstring, T\u003e` to/from a JSON object.\n* Serialize variant types to their stored type. De-serialize variant types using the first matching type.\n* (De-)serialize class types by enumerating their member variables.\n* Omit JSON object field for missing value in `optional\u003cT\u003e`.\n* Skip missing JSON object field for variable with default member initializer in a C++ class.\n* (De-)serialize pointer types such as `shared_ptr\u003cT\u003e` and `unique_ptr\u003cT\u003e`.\n* Back-reference support for (de-)serialization of C++ pointer types via JSON pointer `{\"$ref\": \"/path/to/previous/occurrence\"}`.\n* Serialize C++ objects that share pointers only once. De-serialize back-references as C++ pointers to the same object.\n* Can use the reflection library [Boost.Describe](https://www.boost.org/doc/libs/1_80_0/libs/describe/doc/html/describe.html) for parsing, writing and (de-)serializing enumerations as strings.\n\n## Design goals\n\n### Intuitive syntax\n\n1. Define member variables for JSON serialization and de-serialization within the class definition:\n\n    ```cpp\n    struct Example\n    {\n        bool bool_value = false;\n        std::string string_value;\n        std::vector\u003cstd::string\u003e string_list;\n        std::optional\u003cint\u003e optional_value;\n        UserDefinedType custom_value;\n\n        template \u003ctypename Archive\u003e\n        constexpr auto persist(Archive\u0026 ar)\n        {\n            return ar\n                \u0026 MEMBER_VARIABLE(bool_value)\n                \u0026 MEMBER_VARIABLE(string_value)\n                \u0026 MEMBER_VARIABLE(string_list)\n                \u0026 MEMBER_VARIABLE(optional_value)\n                \u0026 MEMBER_VARIABLE(custom_value)\n                ;\n        }\n    };\n    ```\n\n2. Serialize an object to a JSON string:\n\n    ```cpp\n    Example obj = { true, \"string\", {\"a\",\"b\",\"c\"}, std::nullopt, {\"xyz\"} };\n    auto json = write_to_string(obj);\n    ```\n\n    in which the variable `json` holds:\n\n    ```json\n    {\n        \"bool_value\": true,\n        \"string_value\": \"string\",\n        \"string_list\": [\"a\", \"b\", \"c\"],\n        \"custom_value\": {\"value\": \"xyz\"}\n    }\n    ```\n\n3. Parse a JSON string into an object of the given type:\n\n    ```cpp\n    Example res = parse\u003cExample\u003e(json);\n    ```\n\n### Easy to use\n\n* Copy the `include` folder to your project's header include path, no build or installation required.\n* Get started by including `\u003cpersistence/persistence.hpp\u003e`, which enables all features.\n* Selectively include headers such as `\u003cpersistence/write_object.hpp\u003e` to tackle a specific use case:\n    * Use `\u003cpersistence/write_*.hpp\u003e` for writing a C++ object to a string.\n    * Use `\u003cpersistence/parse_*.hpp\u003e` for parsing a string into a C++ object.\n    * Use `\u003cpersistence/serialize_*.hpp\u003e` for serializing a C++ object to a JSON DOM document.\n    * Use `\u003cpersistence/deserialize_*.hpp\u003e` for de-serializing a JSON DOM document into a C++ object.\n* Use `\u003cpersistence/*_all.hpp\u003e` to import all supported data types for an operation type.\n* Use `\u003cpersistence/object.hpp\u003e` to import helper macro `MEMBER_VARIABLE` only.\n* Use `\u003cpersistence/utility.hpp\u003e` to import helper functions to convert between JSON DOM document and JSON string.\n\n### Extensible\n\nAdd new template specializations to support (de-)serializing new types:\n\n* Specialize `JsonWriter\u003cT\u003e` to support writing new C++ types to JSON string.\n* Specialize `JsonParser\u003cT\u003e` to support parsing new C++ types from JSON string.\n* Specialize `JsonSerializer\u003cT\u003e` to serialize new C++ types to JSON DOM.\n* Specialize `JsonDeserializer\u003cT\u003e` to deserialize new C++ types from JSON DOM.\n\n(De-)serialize, parse and write enumeration types as strings by defining value-to-string and string-to-value conversions.\n\n### Fast and efficient\n\n* Built on top of [RapidJSON](https://rapidjson.org/).\n* Uses RapidJSON [SAX interface](https://rapidjson.org/md_doc_sax.html) for writing and parsing JSON strings directly, bypassing the JSON DOM.\n* Uses [perfect hashing](https://en.wikipedia.org/wiki/Perfect_hash_function) during parsing to look up the member variable corresponding to a JSON object property name.\n* Uses a polymorphic stack to reduce dynamic memory allocations on heap.\n* Infers type and range compatibility at compile-time when possible.\n* Unrolls loops at compile-time for bounded-length data structures such as pairs, tuples and object properties.\n\n### Platform-neutral\n\n* Uses standard C++17 features only (with the exception of RapidJSON engine).\n* Compiles on Linux, MacOS and Windows.\n* Compiles with Clang and MSVC.\n\n## Data transformation modes\n\nThe library supports several transformation modes:\n\n* writing a C++ object directly to a string (without JSON DOM):\n    ```cpp\n    std::string str = write_to_string(obj);\n    ```\n* parsing a string directly into a C++ object (without JSON DOM):\n    ```cpp\n    auto obj = parse\u003cT\u003e(str);\n    ```\n* serializing a C++ object to a JSON DOM document:\n    ```cpp\n    rapidjson::Document doc = serialize_to_document(obj);\n    ```\n* de-serializing a JSON DOM document into a C++ object:\n    ```cpp\n    auto obj = deserialize\u003cT\u003e(doc);\n    ```\n* writing a JSON DOM document to a string (with utility function `document_to_string`)\n* parsing a JSON DOM document from a string (with utility function `string_to_document`)\n* serializing a C++ object to a JSON DOM, and then writing the JSON DOM to a string:\n    ```cpp\n    rapidjson::Document doc = serialize_to_document(obj);\n    std::string str = document_to_string(doc);\n    ```\n* reading a string into a JSON DOM, and then de-serializing the data from JSON DOM into a C++ object:\n    ```cpp\n    rapidjson::Document doc = string_to_document(str);\n    auto obj = deserialize\u003cT\u003e(doc);\n    ```\n\n## Default member initializers\n\nIf a class has a [default member initializer](https://en.cppreference.com/w/cpp/language/data_members#Member_initialization), the value of that member variable is assigned when the object is constructed. As a result, these member variables can be treated as if they were optional for JSON de-serialization and parsing; when the corresponding object key is missing in the source JSON, processing can continue without error. Use the macro `MEMBER_VARIABLE_DEFAULT` to indicate that omitting the JSON property corresponding to this member variable is allowed:\n\n```cpp\nstruct Default\n{\n    template \u003ctypename Archive\u003e\n    constexpr auto persist(Archive\u0026 ar)\n    {\n        return ar\n            \u0026 MEMBER_VARIABLE_DEFAULT(value)\n            ;\n    }\n\nprivate:\n    std::string value = \"default\";\n};\n```\n\nThe same technique can be applied to member variables whose value is assigned in the default constructor.\n\n## Defining persistence in derived classes\n\nThe following example illustrates how to define the `persist` function in a derived class that inherits members from a base class and defines additional member variables of its own:\n\n```cpp\nstruct Base\n{\n    template \u003ctypename Archive\u003e\n    constexpr auto persist(Archive\u0026 ar)\n    {\n        return ar\n            \u0026 MEMBER_VARIABLE(base_member)\n            ;\n    }\n\nprivate:\n    std::string base_member;\n};\n\nstruct Derived : Base\n{\n    template \u003ctypename Archive\u003e\n    constexpr auto persist(Archive\u0026 ar)\n    {\n        return this-\u003eBase::persist(ar)\n            \u0026 MEMBER_VARIABLE(derived_member)\n            ;\n    }\n\nprivate:\n    std::string derived_member;\n};\n```\n\n## Enumeration to string conversion\n\nIn order to (de-)serialize, parse and write enumeration types as strings, define value-to-string and string-to-value conversions with the type trait class `enum_traits`:\n\n```cpp\nnamespace persistence\n{\n    template\u003c\u003e\n    struct enum_traits\u003cMyEnum\u003e\n    {\n        static std::string_view to_string(MyEnum value)\n        {\n            // return a distinct string literal for each enumeration value\n            return std::string_view();\n        }\n\n        static bool from_string(const std::string_view\u0026 name, MyEnum\u0026 value)\n        {\n            // assign enumeration value based on string literal\n            value = MyEnum();\n\n            // return true if value has been assigned; false on no match\n            return true;\n        }\n    };\n}\n```\n\nUse utility function `make_enum_converter` and class `EnumConverter\u003cE, N\u003e` to implement `to_string` and `from_string` with less boilerplate code.\n\nIf the reflection library [Boost.Describe](https://www.boost.org/doc/libs/1_80_0/libs/describe/doc/html/describe.html) is enabled, provide reflection metadata for enumerations with `BOOST_DESCRIBE_ENUM`. The string names assigned with this macro are used in parsing, writing and (de-)serializing enumerations.\n\nIn order to enable Boost.Describe reflections, compile your project with the preprocessor macro `PERSISTENCE_BOOST_DESCRIBE`. Make sure the following headers are available:\n\n```cpp\n#include \u003cboost/describe/enum_to_string.hpp\u003e\n#include \u003cboost/describe/enum_from_string.hpp\u003e\n```\n\n## Error reporting\n\nFunctions that take both a source and a target object reference return a boolean result and throw no exceptions. Functions that take only a source argument and return a target object value throw exceptions on error.\n\nConsider the following C++ code that invokes the parser:\n```cpp\ntry {\n    parse\u003cExample\u003e(\"{\\\"bool_value\\\": true, []}\");\n} catch (JsonParseError\u0026 e) {\n    std::cout \u003c\u003c e.what() \u003c\u003c std::endl;\n}\n```\n\nThere is a syntax error in the JSON string. Running the above code prints:\n```\nparse error at offset 21: Missing a name for object member.\n```\n\nTake another example with a mismatch for the property value type:\n```cpp\ntry {\n    parse\u003cExample\u003e(\"{\\\"bool_value\\\": true, \\\"string_value\\\": []}\");\n} catch (JsonParseError\u0026 e) {\n    std::cout \u003c\u003c e.what() \u003c\u003c std::endl;\n}\n```\n\nEven though the above JSON string is syntactically correct, a JSON array cannot be cast into a C++ string, which produces an error:\n```\nparse error at offset 38: Terminate parsing due to Handler error.\n```\n\nSimilarly, the deserializer not only reports the nature of the error encountered but also its location with a [JSON Pointer](https://www.rfc-editor.org/rfc/rfc6901). Consider the following:\n```cpp\ntry {\n    deserialize\u003cExample\u003e(\n        \"{\"\n            \"\\\"bool_value\\\": true,\"\n            \"\\\"string_value\\\": \\\"lorem ipsum\\\",\"\n            \"\\\"string_list\\\": [\\\"a\\\",23]\"\n        \"}\"\n    );\n} catch (JsonDeserializationError\u0026 e) {\n    std::cout \u003c\u003c e.what() \u003c\u003c std::endl;\n}\n```\n\nNotice how the second element of `string_list` (a C++ `vector\u003cstring\u003e`) has the wrong data type: a JSON number instead of a JSON string. The error message identifies the location: `/string_list` to select the property in the root object and `/1` to identify the second element in the array (with zero-based indexing):\n```\nwrong JSON data type; expected: string at /string_list/1\n```\n\n## Generating JSON schema\n\nThe library understands the most common C++ types and can emit corresponding [JSON Schema](https://json-schema.org/) types. For example, take the following C++ code:\n\n```cpp\nstd::cout \u003c\u003c schema_document_to_string\u003cExample\u003e() \u003c\u003c std::endl;\n```\n\nIn this case, the output may look like as follows:\n\n```json\n{\n    \"$schema\": \"https://json-schema.org/draft/2020-12/schema\",\n    \"definitions\": {\n        \"UserDefinedType\": {\n            \"type\": \"object\",\n            \"properties\": {\n                \"value\": { \"type\": \"string\" }\n            },\n            \"required\": [\"value\"],\n            \"additionalProperties\": false\n        }\n    },\n    \"type\": \"object\",\n    \"properties\": {\n        \"bool_value\": {\n            \"type\": \"boolean\"\n        },\n        \"string_value\": {\n            \"type\": \"string\"\n        },\n        \"string_list\": {\n            \"type\": \"array\",\n            \"items\": { \"type\": \"string\" }\n        },\n        \"optional_value\": {\n            \"type\": \"integer\",\n            \"minimum\": -2147483648,\n            \"maximum\": 2147483647\n        },\n        \"custom_value\": {\n            \"$ref\": \"#/definitions/UserDefinedType\"\n        }\n    },\n    \"required\": [\n        \"bool_value\",\n        \"string_value\",\n        \"string_list\",\n        \"custom_value\"\n    ],\n    \"additionalProperties\": false\n}\n```\n\n## Performance\n\nThe following table shows relative performance of writing, parsing and (de-)serializing a C++ `vector` object of 100,000 elements. Each element is a composite object holding (vectors of) boolean, integer and string values. When represented as JSON, the string takes approximately 100 MB. DOM is the `Document` object constructed by RapidJSON when de-serializing a JSON string.\n\n| Case | Operation                                                    | Duration |\n|:---- |:------------------------------------------------------------ | --------:|\n|    1 | write object to string                                       |   310 ms |\n|    2 | parse object from string                                     |   672 ms |\n|    3 | serialize DOM to string                                      |   336 ms |\n|    4 | deserialize DOM from string                                  |   411 ms |\n|    5 | serialize object to DOM                                      |   223 ms |\n|    6 | deserialize object from DOM with exceptions disabled         |   365 ms |\n|    7 | deserialize object from DOM with exceptions enabled          |   386 ms |\n\nCases 1 and 2 capture the end-to-end performance of this header-only library. Cases 3 and 4 reflect functionality provided by RapidJSON out of the box, and act as reference values; accessors are needed to get data out of DOM instead of manipulating C++ objects directly. Cases 5, 6 and 7 help estimate the relative cost of (de-)serializing an object to/from DOM, as a step towards a JSON string. Comparison of Case 1 with Cases 3 + 5, and of Case 2 with Cases 4 + (6 or 7) gives an estimate of the savings gained by translating from a C++ object directly to/from a JSON string.\n\n## Limitations and workarounds\n\nJSON parser does not support back-references (`{\"$ref\": \"/path/to/previous/occurrence\"}`); parsing pointer-like types always creates a new instance. When back-references are present, read the JSON string into a JSON DOM with the utility function `string_to_document`, and then de-serialize the data from JSON DOM with `deserialize`.\n\nParsing and de-serializing raw pointers is not permitted due to lack of clarity around ownership. Use `unique_ptr` and `shared_ptr` instead. Writing and serializing raw pointers is allowed, the pointee object is written.\n\nJSON parser does not support variant types. Instead, read the JSON string into a JSON DOM with the utility function `string_to_document`, and then de-serialize the data from JSON DOM with `deserialize`. JSON writer, serializer and de-serializer support variant types.\n\n## Comparison to other libraries\n\nUnlike [Boost.JSON](https://www.boost.org/doc/libs/1_80_0/libs/json/doc/html/index.html) and [nlohmann/json](https://github.com/nlohmann/json), this library does not introduce a variant JSON `value` type whose contents you can manipulate with accessors at run time. Instead, this library uses the original C++ data types, and employs compile-time inference to perform the appropriate action on parsing, writing and (de-)serialization.\n","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fhunyadi%2Fjson-persistence","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fhunyadi%2Fjson-persistence","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fhunyadi%2Fjson-persistence/lists"}