mirror of
https://github.com/nlohmann/json.git
synced 2026-07-22 11:43:02 +04:00
Compare commits
121 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| ff9a03237d | |||
| 1342982e7d | |||
| 48e99f4145 | |||
| 483310ef04 | |||
| 0a9a593da9 | |||
| 9c5d766c77 | |||
| 7bc7ca0e06 | |||
| e86d443881 | |||
| d2962f1fff | |||
| ee18d823cf | |||
| cb2fdb38a4 | |||
| c9c3d3de86 | |||
| a72084fa16 | |||
| cb1c51b1d0 | |||
| 279d757031 | |||
| 9a231845c2 | |||
| 69c180d665 | |||
| 4deadb2473 | |||
| f2f73132b2 | |||
| aa3e17802f | |||
| 7bd119baba | |||
| 14aee2f37d | |||
| 8084adee40 | |||
| 4308c54cef | |||
| 5c7c81d6fc | |||
| 0d8a3f1278 | |||
| 74caa1b78d | |||
| 6fa04ddf18 | |||
| 96be658738 | |||
| 02f17c1018 | |||
| 9446cb8fa1 | |||
| 3d26d62a39 | |||
| c0aa9485a6 | |||
| cf7c116a75 | |||
| fa76a96d90 | |||
| 74f72a3c59 | |||
| 7823c2ade7 | |||
| 0a7e3eb0e7 | |||
| 7cb41d25ca | |||
| 1b402111d4 | |||
| 1ce3fa5bc3 | |||
| b14b932a24 | |||
| 9747b9a034 | |||
| d62f424acb | |||
| 6b276104d1 | |||
| bbee86a3d1 | |||
| 094c066118 | |||
| de6545005b | |||
| c25905a6df | |||
| 0451d43da5 | |||
| d2014a5a79 | |||
| bc67341534 | |||
| 3d161f7495 | |||
| de508bc2d8 | |||
| 7a570ae601 | |||
| 8b3e448529 | |||
| fab37adabc | |||
| 0b14a60e6f | |||
| 06c7d96cae | |||
| c5b048860d | |||
| 980085f8fb | |||
| 2edffa5d7b | |||
| 3f8f635b63 | |||
| baa3082b26 | |||
| 8ac879d12d | |||
| 57e7092dfa | |||
| 72e81f5b40 | |||
| 5723019bbd | |||
| 0b82731bef | |||
| cd01edbea6 | |||
| 90f3fa4749 | |||
| c5cf12c0d5 | |||
| 954dedad9d | |||
| 71490250f6 | |||
| 5875ebf0ac | |||
| c789bb9b27 | |||
| e567fb9a17 | |||
| 0ad5544857 | |||
| efa0173f9b | |||
| f3ded41873 | |||
| 404c03b9f0 | |||
| b0d0937680 | |||
| 1d305a9c1b | |||
| 2e3e066195 | |||
| 3f8c22f631 | |||
| a9409755c7 | |||
| 702a1c2a48 | |||
| a0711a40c0 | |||
| e41981a751 | |||
| bd06f48825 | |||
| cb1747470b | |||
| 29e9ba0511 | |||
| de895b1d1a | |||
| b0759e09b1 | |||
| 32cf7af82a | |||
| 6c9075c692 | |||
| 6ff5604324 | |||
| 9cd1c63d00 | |||
| 4ce072a05e | |||
| a40ca752f0 | |||
| c818701d98 | |||
| 1a2fb08d1c | |||
| fb8527384c | |||
| a46ad99086 | |||
| 28c1cbfef9 | |||
| 1a095c93fb | |||
| fd94ec80c7 | |||
| 9ed446a688 | |||
| ac48b5c374 | |||
| e3f1e1d35b | |||
| 41cbe4b3ef | |||
| 364a48d9d6 | |||
| 836d436a40 | |||
| ab14172173 | |||
| b014c90f94 | |||
| a87fd638da | |||
| 344ced4012 | |||
| 1bda49b536 | |||
| 5de3c82c9a | |||
| 6a2266aff4 | |||
| 55f10f44a9 |
@@ -1,74 +0,0 @@
|
||||
[](http://issuestats.com/github/nlohmann/json) [](http://issuestats.com/github/nlohmann/json)
|
||||
|
||||
# How to contribute
|
||||
|
||||
This project started as a little excuse to exercise some of the cool new C++11 features. Over time, people actually started to use the JSON library (yey!) and started to help improve it by proposing features, finding bugs, or even fixing my mistakes. I am really [thankful](https://github.com/nlohmann/json/blob/master/README.md#thanks) for this and try to keep track of all the helpers.
|
||||
|
||||
To make it as easy as possible for you to contribute and for me to keep an overview, here are a few guidelines which should help us avoid all kinds of unnecessary work or disappointment. And of course, this document is subject to discussion, so please [create an issue](https://github.com/nlohmann/json/issues/new) or a pull request if you find a way to improve it!
|
||||
|
||||
## Private reports
|
||||
|
||||
Usually, all issues are tracked publicly on [Github](https://github.com/nlohmann/json/issues). If you want to make a private report (e.g., for a vulnerability or to attach an example that is not meant to be publisheed), please send an email to <mail@nlohmann.me>.
|
||||
|
||||
## Prerequisites
|
||||
|
||||
Please [create an issue](https://github.com/nlohmann/json/issues/new), assuming one does not already exist, and describe your concern. Note you need a [GitHub account](https://github.com/signup/free) for this.
|
||||
|
||||
If you want propose changes to the code, you need to download the [`re2c`](http://re2c.org) tool.
|
||||
|
||||
## Describe your issue
|
||||
|
||||
Clearly describe the issue:
|
||||
|
||||
- If it is a bug, please describe how to **reproduce** it. If possible, attach a complete example which demonstrates the error. Please also state what you **expected** to happen instead of the error.
|
||||
- If you propose a change or addition, try to give an **example** how the improved code could look like or how to use it.
|
||||
- If you found a compilation error, please tell us which **compiler** (version and operating system) you used and paste the (relevant part of) the error messages to the ticket.
|
||||
|
||||
## Files to change
|
||||
|
||||
There are currently two files which need to be edited:
|
||||
|
||||
1. [`src/json.hpp.re2c`](https://github.com/nlohmann/json/blob/master/src/json.hpp.re2c) (note the `.re2c` suffix) - This file contains a comment section which describes the JSON lexic. This section is translated by [`re2c`](http://re2c.org) into file [`src/json.hpp`](https://github.com/nlohmann/json/blob/master/src/json.hpp) which is plain "vanilla" C++11 code. (In fact, the generated lexer consists of some hundred lines of `goto`s, which is a hint you never want to edit this file...).
|
||||
|
||||
If you only edit file `src/json.hpp` (without the `.re2c` suffix), your changes will be overwritten as soon as the lexer is touched again. To generate the `src/json.hpp` file which is actually used during compilation of the tests and all other code, please execute
|
||||
|
||||
```sh
|
||||
make re2c
|
||||
```
|
||||
|
||||
To run [`re2c`](http://re2c.org) and generate/overwrite file `src/json.hpp` with your changes in file `src/json.hpp.re2c`.
|
||||
|
||||
|
||||
2. [`test/src/unit.cpp`](https://github.com/nlohmann/json/blob/master/test/unit.cpp) - This contains the [Catch](https://github.com/philsquared/Catch) unit tests which currently cover [100 %](https://coveralls.io/github/nlohmann/json) of the library's code.
|
||||
|
||||
If you add or change a feature, please also add a unit test to this file. The unit tests can be compiled and executed with
|
||||
|
||||
```sh
|
||||
make check
|
||||
```
|
||||
|
||||
The test cases are also executed with several different compilers on [Travis](https://travis-ci.org/nlohmann/json) once you open a pull request.
|
||||
|
||||
Please understand that I cannot accept pull requests changing only file `src/json.hpp`.
|
||||
|
||||
|
||||
## Note
|
||||
|
||||
- If you open a pull request, the code will be automatically tested with [Valgrind](http://valgrind.org)'s Memcheck tool to detect memory leaks. Please be aware that the execution with Valgrind _may_ in rare cases yield different behavior than running the code directly. This can result in failing unit tests which run successfully without Valgrind.
|
||||
- There is a Makefile target `make pretty` which runs [Artistic Style](http://astyle.sourceforge.net) to fix indentation. If possible, run it before opening the pull request. Otherwise, we shall run it afterward.
|
||||
|
||||
## Please don't
|
||||
|
||||
- Only make changes to file `src/json.hpp` -- please read the paragraph above and understand why `src/json.hpp.re2c` exists.
|
||||
- The C++11 support varies between different **compilers** and versions. Please note the [list of supported compilers](https://github.com/nlohmann/json/blob/master/README.md#supported-compilers). Some compilers like GCC 4.8 (and earlier), Clang 3.3 (and earlier), or Microsoft Visual Studio 13.0 and earlier are known not to work due to missing or incomplete C++11 support. Please refrain from proposing changes that work around these compiler's limitations with `#ifdef`s or other means.
|
||||
- Specifically, I am aware of compilation problems with **Microsoft Visual Studio** (there even is an [issue label](https://github.com/nlohmann/json/issues?utf8=✓&q=label%3A%22visual+studio%22+) for these kind of bugs). I understand that even in 2016, complete C++11 support isn't there yet. But please also understand that I do not want to drop features or uglify the code just to make Microsoft's sub-standard compiler happy. The past has shown that there are ways to express the functionality such that the code compiles with the most recent MSVC - unfortunately, this is not the main objective of the project.
|
||||
- Please refrain from proposing changes that would **break [JSON](http://json.org) conformance**. If you propose a conformant extension of JSON to be supported by the library, please motivate this extension.
|
||||
- Please do not open pull requests that address **multiple issues**.
|
||||
|
||||
## Wanted
|
||||
|
||||
The following areas really need contribution:
|
||||
|
||||
- Extending the **continuous integration** toward more exotic compilers such as Android NDK, Intel's Compiler, or the bleeding-edge versions of GCC or Clang.
|
||||
- Improving the efficiency of the **JSON parser**. The current parser is implemented as a naive recursive descent parser with hand coded string handling. More sophisticated approaches like LALR parsers would be really appreciated. That said, parser generators like Bison or ANTLR do not play nice with single-header files -- I really would like to keep the parser inside the `json.hpp` header, and I am not aware of approaches similar to [`re2c`](http://re2c.org) for parsing.
|
||||
- Extending and updating existing **benchmarks** to include (the most recent version of) this library. Though efficiency is not everything, speed and memory consumption are very important characteristics for C++ developers, so having proper comparisons would be interesting.
|
||||
@@ -1,46 +0,0 @@
|
||||
|
||||
## Files to change
|
||||
|
||||
There are currently two files which need to be edited:
|
||||
|
||||
1. [`src/json.hpp.re2c`](https://github.com/nlohmann/json/blob/master/src/json.hpp.re2c) (note the `.re2c` suffix) - This file contains a comment section which describes the JSON lexic. This section is translated by [`re2c`](http://re2c.org) into file [`src/json.hpp`](https://github.com/nlohmann/json/blob/master/src/json.hpp) which is plain "vanilla" C++11 code. (In fact, the generated lexer consists of some hundred lines of `goto`s, which is a hint you never want to edit this file...).
|
||||
|
||||
If you only edit file `src/json.hpp` (without the `.re2c` suffix), your changes will be overwritten as soon as the lexer is touched again. To generate the `src/json.hpp` file which is actually used during compilation of the tests and all other code, please execute
|
||||
|
||||
```sh
|
||||
make re2c
|
||||
```
|
||||
|
||||
To run [`re2c`](http://re2c.org) and generate/overwrite file `src/json.hpp` with your changes in file `src/json.hpp.re2c`.
|
||||
|
||||
|
||||
2. [`test/src/unit.cpp`](https://github.com/nlohmann/json/blob/master/test/unit.cpp) - This contains the [Catch](https://github.com/philsquared/Catch) unit tests which currently cover [100 %](https://coveralls.io/github/nlohmann/json) of the library's code.
|
||||
|
||||
If you add or change a feature, please also add a unit test to this file. The unit tests can be compiled with
|
||||
|
||||
```sh
|
||||
make
|
||||
```
|
||||
|
||||
and can be executed with
|
||||
|
||||
```sh
|
||||
./json_unit
|
||||
```
|
||||
|
||||
The test cases are also executed with several different compilers on [Travis](https://travis-ci.org/nlohmann/json) once you open a pull request.
|
||||
|
||||
Please understand that I cannot accept pull requests changing only file `src/json.hpp`.
|
||||
|
||||
|
||||
## Note
|
||||
|
||||
- If you open a pull request, the code will be automatically tested with [Valgrind](http://valgrind.org)'s Memcheck tool to detect memory leaks. Please be aware that the execution with Valgrind _may_ in rare cases yield different behavior than running the code directly. This can result in failing unit tests which run successfully without Valgrind.
|
||||
|
||||
## Please don't
|
||||
|
||||
- Only make changes to file `src/json.hpp` -- please read the paragraph above and understand why `src/json.hpp.re2c` exists.
|
||||
- The C++11 support varies between different **compilers** and versions. Please note the [list of supported compilers](https://github.com/nlohmann/json/blob/master/README.md#supported-compilers). Some compilers like GCC 4.8 (and earlier), Clang 3.3 (and earlier), or Microsoft Visual Studio 13.0 and earlier are known not to work due to missing or incomplete C++11 support. Please refrain from proposing changes that work around these compiler's limitations with `#ifdef`s or other means.
|
||||
- Specifically, I am aware of compilation problems with **Microsoft Visual Studio** (there even is an [issue label](https://github.com/nlohmann/json/issues?utf8=✓&q=label%3A%22visual+studio%22+) for these kind of bugs). I understand that even in 2016, complete C++11 support isn't there yet. But please also understand that I do not want to drop features or uglify the code just to make Microsoft's sub-standard compiler happy. The past has shown that there are ways to express the functionality such that the code compiles with the most recent MSVC - unfortunately, this is not the main objective of the project.
|
||||
- Please refrain from proposing changes that would **break [JSON](http://json.org) conformance**. If you propose a conformant extension of JSON to be supported by the library, please motivate this extension.
|
||||
- Please do not open pull requests that address **multiple issues**.
|
||||
-16
@@ -1,16 +0,0 @@
|
||||
json_unit
|
||||
json_benchmarks
|
||||
fuzz-testing
|
||||
|
||||
*.dSYM
|
||||
*.o
|
||||
*.gcno
|
||||
*.gcda
|
||||
|
||||
working
|
||||
|
||||
doc/xml
|
||||
doc/html
|
||||
me.nlohmann.json.docset
|
||||
|
||||
benchmarks/files/numbers/*.json
|
||||
-308
@@ -1,308 +0,0 @@
|
||||
#########################
|
||||
# project configuration #
|
||||
#########################
|
||||
|
||||
# C++ project
|
||||
language: cpp
|
||||
|
||||
dist: trusty
|
||||
sudo: required
|
||||
|
||||
|
||||
###################
|
||||
# global settings #
|
||||
###################
|
||||
|
||||
env:
|
||||
global:
|
||||
# The next declaration is the encrypted COVERITY_SCAN_TOKEN, created
|
||||
# via the "travis encrypt" command using the project repo's public key
|
||||
- secure: "m89SSgE+ASLO38rSKx7MTXK3n5NkP9bIx95jwY71YEiuFzib30PDJ/DifKnXxBjvy/AkCGztErQRk/8ZCvq+4HXozU2knEGnL/RUitvlwbhzfh2D4lmS3BvWBGS3N3NewoPBrRmdcvnT0xjOGXxtZaJ3P74TkB9GBnlz/HmKORA="
|
||||
|
||||
|
||||
################
|
||||
# build matrix #
|
||||
################
|
||||
|
||||
matrix:
|
||||
include:
|
||||
|
||||
# Valgrind
|
||||
|
||||
- os: linux
|
||||
compiler: gcc
|
||||
env:
|
||||
- COMPILER=g++-4.9
|
||||
- SPECIAL=valgrind
|
||||
addons:
|
||||
apt:
|
||||
sources: ['ubuntu-toolchain-r-test']
|
||||
packages: [g++-4.9, valgrind]
|
||||
after_success:
|
||||
- valgrind --error-exitcode=1 --leak-check=full test/json_unit
|
||||
|
||||
# cppcheck
|
||||
|
||||
- os: linux
|
||||
compiler: gcc
|
||||
env:
|
||||
- COMPILER=g++-4.9
|
||||
- SPECIAL=cppcheck
|
||||
addons:
|
||||
apt:
|
||||
sources: ['ubuntu-toolchain-r-test']
|
||||
packages: [g++-4.9, cppcheck]
|
||||
after_success:
|
||||
- make cppcheck
|
||||
|
||||
# Coveralls (http://gronlier.fr/blog/2015/01/adding-code-coverage-to-your-c-project/)
|
||||
|
||||
- os: linux
|
||||
compiler: gcc
|
||||
addons:
|
||||
apt:
|
||||
sources: ['ubuntu-toolchain-r-test']
|
||||
packages: ['g++-4.9', 'ruby']
|
||||
before_script:
|
||||
- wget http://ftp.de.debian.org/debian/pool/main/l/lcov/lcov_1.11.orig.tar.gz
|
||||
- tar xf lcov_1.11.orig.tar.gz
|
||||
- sudo make -C lcov-1.11/ install
|
||||
- gem install coveralls-lcov
|
||||
after_success:
|
||||
- make clean
|
||||
- CXXFLAGS="--coverage -g -O0" CPPFLAGS="-DNDEBUG" make
|
||||
- test/json_unit "*"
|
||||
- coveralls --build-root test --exclude src/catch.hpp --exclude src/unit-algorithms.cpp --exclude src/unit-allocator.cpp --exclude src/unit-capacity.cpp --exclude src/unit-class_const_iterator.cpp --exclude src/unit-class_iterator.cpp --exclude src/unit-class_lexer.cpp --exclude src/unit-class_parser.cpp --exclude src/unit-comparison.cpp --exclude src/unit-concepts.cpp --exclude src/unit-constructor1.cpp --exclude src/unit-constructor2.cpp --exclude src/unit-convenience.cpp --exclude src/unit-conversions.cpp --exclude src/unit-deserialization.cpp --exclude src/unit-element_access1.cpp --exclude src/unit-element_access2.cpp --exclude src/unit-inspection.cpp --exclude src/unit-iterator_wrapper.cpp --exclude src/unit-iterators1.cpp --exclude src/unit-iterators2.cpp --exclude src/unit-json_patch.cpp --exclude src/unit-json_pointer.cpp --exclude src/unit-modifiers.cpp --exclude src/unit-pointer_access.cpp --exclude src/unit-readme.cpp --exclude src/unit-reference_access.cpp --exclude src/unit-regression.cpp --exclude src/unit-serialization.cpp --exclude src/unit-testsuites.cpp --exclude src/unit-unicode.cpp --include ../src/json.hpp --gcov-options '\-lp' --gcov 'gcov-4.9'
|
||||
- lcov --directory src --directory test/src --capture --output-file coverage.info --rc lcov_branch_coverage=1 --no-external
|
||||
- lcov --remove coverage.info 'test/src/*' --output-file coverage.info --rc lcov_branch_coverage=1
|
||||
- lcov --list coverage.info --rc lcov_branch_coverage=1
|
||||
- coveralls-lcov --repo-token F9bs4Nop10JRgqPQXRcifyQKYhb3FczkS coverage.info
|
||||
env:
|
||||
- COMPILER=g++-4.9
|
||||
- SPECIAL=coveralls
|
||||
|
||||
# Coverity (only for branch coverity_scan)
|
||||
|
||||
- os: linux
|
||||
compiler: gcc
|
||||
before_install: echo -n | openssl s_client -connect scan.coverity.com:443 | sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p' | sudo tee -a /etc/ssl/certs/ca-certificates.crt
|
||||
addons:
|
||||
apt:
|
||||
sources: ['ubuntu-toolchain-r-test']
|
||||
packages: ['g++-5', 'valgrind']
|
||||
coverity_scan:
|
||||
project:
|
||||
name: "nlohmann/json"
|
||||
description: "Build submitted via Travis CI"
|
||||
notification_email: niels.lohmann@gmail.com
|
||||
build_command_prepend: "make clean ; sudo cp $(which g++-5) $(which g++)"
|
||||
build_command: "make"
|
||||
branch_pattern: coverity_scan
|
||||
env:
|
||||
- COMPILER=g++-5
|
||||
- SPECIAL=coverity
|
||||
|
||||
# OSX / Clang
|
||||
|
||||
- os: osx
|
||||
osx_image: beta-xcode6.1
|
||||
|
||||
- os: osx
|
||||
osx_image: beta-xcode6.2
|
||||
|
||||
- os: osx
|
||||
osx_image: beta-xcode6.3
|
||||
|
||||
- os: osx
|
||||
osx_image: xcode6.4
|
||||
|
||||
- os: osx
|
||||
osx_image: xcode7.1
|
||||
|
||||
- os: osx
|
||||
osx_image: xcode7.2
|
||||
|
||||
- os: osx
|
||||
osx_image: xcode7.3
|
||||
|
||||
- os: osx
|
||||
osx_image: xcode8
|
||||
|
||||
# Linux / GCC
|
||||
|
||||
- os: linux
|
||||
compiler: gcc
|
||||
env: COMPILER=g++-4.9
|
||||
addons:
|
||||
apt:
|
||||
sources: ['ubuntu-toolchain-r-test']
|
||||
packages: g++-4.9
|
||||
|
||||
- os: linux
|
||||
compiler: gcc
|
||||
env: COMPILER=g++-5
|
||||
addons:
|
||||
apt:
|
||||
sources: ['ubuntu-toolchain-r-test']
|
||||
packages: g++-5
|
||||
|
||||
- os: linux
|
||||
compiler: gcc
|
||||
env: COMPILER=g++-6
|
||||
addons:
|
||||
apt:
|
||||
sources: ['ubuntu-toolchain-r-test']
|
||||
packages: g++-6
|
||||
|
||||
# Linux / Clang
|
||||
|
||||
- os: linux
|
||||
env: LLVM_VERSION=3.6.0
|
||||
compiler: clang
|
||||
|
||||
- os: linux
|
||||
env: LLVM_VERSION=3.6.1
|
||||
compiler: clang
|
||||
|
||||
- os: linux
|
||||
env: LLVM_VERSION=3.6.2
|
||||
compiler: clang
|
||||
|
||||
- os: linux
|
||||
env: LLVM_VERSION=3.7.0
|
||||
compiler: clang
|
||||
|
||||
- os: linux
|
||||
env: LLVM_VERSION=3.7.1
|
||||
compiler: clang
|
||||
|
||||
- os: linux
|
||||
env: LLVM_VERSION=3.8.0
|
||||
compiler: clang
|
||||
|
||||
- os: linux
|
||||
env: LLVM_VERSION=3.8.1
|
||||
compiler: clang
|
||||
|
||||
#####################
|
||||
# installation step #
|
||||
#####################
|
||||
|
||||
# set directories to cache
|
||||
cache:
|
||||
directories:
|
||||
- ${TRAVIS_BUILD_DIR}/deps/llvm-3.6.2
|
||||
- ${TRAVIS_BUILD_DIR}/deps/llvm-3.6.1
|
||||
- ${TRAVIS_BUILD_DIR}/deps/llvm-3.6.0
|
||||
- ${TRAVIS_BUILD_DIR}/deps/llvm-3.7.0
|
||||
- ${TRAVIS_BUILD_DIR}/deps/llvm-3.7.1
|
||||
- ${TRAVIS_BUILD_DIR}/deps/llvm-3.8.0
|
||||
- ${TRAVIS_BUILD_DIR}/deps/llvm-3.8.1
|
||||
|
||||
|
||||
install:
|
||||
# create deps dir if not existing
|
||||
- DEPS_DIR="${TRAVIS_BUILD_DIR}/deps"
|
||||
- mkdir -p ${DEPS_DIR}
|
||||
|
||||
# make sure CXX is correctly set
|
||||
- if [[ "${COMPILER}" != "" ]]; then export CXX=${COMPILER}; fi
|
||||
|
||||
# install LLVM/clang when LLVM_VERSION is set
|
||||
- |
|
||||
if [[ "${LLVM_VERSION}" != "" ]]; then
|
||||
LLVM_DIR=${DEPS_DIR}/llvm-${LLVM_VERSION}
|
||||
if [[ -z "$(ls -A ${LLVM_DIR})" ]]; then
|
||||
travis_retry wget --quiet https://cmake.org/files/v3.6/cmake-3.6.1.tar.gz
|
||||
tar xfz cmake-3.6.1.tar.gz
|
||||
(cd cmake-3.6.1 && ./configure --prefix=${LLVM_DIR}/cmake && make install)
|
||||
export PATH="${LLVM_DIR}/cmake/bin:${PATH}"
|
||||
LLVM_URL="http://llvm.org/releases/${LLVM_VERSION}/llvm-${LLVM_VERSION}.src.tar.xz"
|
||||
LIBCXX_URL="http://llvm.org/releases/${LLVM_VERSION}/libcxx-${LLVM_VERSION}.src.tar.xz"
|
||||
LIBCXXABI_URL="http://llvm.org/releases/${LLVM_VERSION}/libcxxabi-${LLVM_VERSION}.src.tar.xz"
|
||||
CLANG_URL="http://llvm.org/releases/${LLVM_VERSION}/clang+llvm-${LLVM_VERSION}-x86_64-linux-gnu-ubuntu-14.04.tar.xz"
|
||||
mkdir -p ${LLVM_DIR} ${LLVM_DIR}/build ${LLVM_DIR}/projects/libcxx ${LLVM_DIR}/projects/libcxxabi ${LLVM_DIR}/clang
|
||||
travis_retry wget --quiet -O - ${LLVM_URL} | tar --strip-components=1 -xJ -C ${LLVM_DIR}
|
||||
travis_retry wget --quiet -O - ${LIBCXX_URL} | tar --strip-components=1 -xJ -C ${LLVM_DIR}/projects/libcxx
|
||||
travis_retry wget --quiet -O - ${LIBCXXABI_URL} | tar --strip-components=1 -xJ -C ${LLVM_DIR}/projects/libcxxabi
|
||||
travis_retry wget --quiet -O - ${CLANG_URL} | tar --strip-components=1 -xJ -C ${LLVM_DIR}/clang
|
||||
(cd ${LLVM_DIR}/build && cmake .. -DCMAKE_INSTALL_PREFIX=${LLVM_DIR}/install -DCMAKE_CXX_COMPILER=clang++)
|
||||
(cd ${LLVM_DIR}/build/projects/libcxx && make install -j2)
|
||||
(cd ${LLVM_DIR}/build/projects/libcxxabi && make install -j2)
|
||||
fi
|
||||
export CXXFLAGS="-nostdinc++ -isystem ${LLVM_DIR}/install/include/c++/v1"
|
||||
export LDFLAGS="-L ${LLVM_DIR}/install/lib -l c++ -l c++abi"
|
||||
export LD_LIBRARY_PATH="${LD_LIBRARY_PATH}:${LLVM_DIR}/install/lib"
|
||||
export PATH="${LLVM_DIR}/clang/bin:${PATH}"
|
||||
fi
|
||||
|
||||
################
|
||||
# build script #
|
||||
################
|
||||
|
||||
script:
|
||||
# show OS/compiler version
|
||||
- uname -a
|
||||
- $CXX --version
|
||||
|
||||
# compile
|
||||
- make
|
||||
|
||||
# execute unit tests
|
||||
- test/json_unit "*"
|
||||
|
||||
# check if homebrew works (only checks develop branch)
|
||||
- if [ `which brew` ]; then
|
||||
brew update ;
|
||||
brew tap nlohmann/json ;
|
||||
brew install nlohmann_json --HEAD ;
|
||||
brew test nlohmann_json ;
|
||||
fi
|
||||
|
||||
#language: cpp
|
||||
#
|
||||
#dist: trusty
|
||||
#sudo: required
|
||||
#
|
||||
#env:
|
||||
# global:
|
||||
# # The next declaration is the encrypted COVERITY_SCAN_TOKEN, created
|
||||
# # via the "travis encrypt" command using the project repo's public key
|
||||
# - secure: "m89SSgE+ASLO38rSKx7MTXK3n5NkP9bIx95jwY71YEiuFzib30PDJ/DifKnXxBjvy/AkCGztErQRk/8ZCvq+4HXozU2knEGnL/RUitvlwbhzfh2D4lmS3BvWBGS3N3NewoPBrRmdcvnT0xjOGXxtZaJ3P74TkB9GBnlz/HmKORA="
|
||||
#
|
||||
## from http://stackoverflow.com/a/32127147/266378
|
||||
#matrix:
|
||||
# include:
|
||||
# - os: linux
|
||||
# compiler: gcc
|
||||
# addons:
|
||||
# apt:
|
||||
# sources: ['ubuntu-toolchain-r-test']
|
||||
# packages: ['g++-4.9', 'valgrind', 'python-pip', 'python-yaml']
|
||||
# before_script:
|
||||
# - pip install --user git+git://github.com/eddyxu/cpp-coveralls.git
|
||||
# after_success:
|
||||
# - make clean
|
||||
# - touch src/json.hpp
|
||||
# - make json_unit CXXFLAGS="-fprofile-arcs -ftest-coverage -std=c++11 -lstdc++" CXX=$COMPILER
|
||||
# - test/json_unit "*"
|
||||
# - coveralls --build-root test --exclude src/catch.hpp --exclude src/unit-algorithms.cpp --exclude src/unit-allocator.cpp --exclude src/unit-capacity.cpp --exclude src/unit-class_const_iterator.cpp --exclude src/unit-class_iterator.cpp --exclude src/unit-class_lexer.cpp --exclude src/unit-class_parser.cpp --exclude src/unit-comparison.cpp --exclude src/unit-concepts.cpp --exclude src/unit-constructor1.cpp --exclude src/unit-constructor2.cpp --exclude src/unit-convenience.cpp --exclude src/unit-conversions.cpp --exclude src/unit-deserialization.cpp --exclude src/unit-element_access1.cpp --exclude src/unit-element_access2.cpp --exclude src/unit-inspection.cpp --exclude src/unit-iterator_wrapper.cpp --exclude src/unit-iterators1.cpp --exclude src/unit-iterators2.cpp --exclude src/unit-json_patch.cpp --exclude src/unit-json_pointer.cpp --exclude src/unit-modifiers.cpp --exclude src/unit-pointer_access.cpp --exclude src/unit-readme.cpp --exclude src/unit-reference_access.cpp --exclude src/unit-regression.cpp --exclude src/unit-serialization.cpp --exclude src/unit-testsuites.cpp --exclude src/unit-unicode.cpp --include ../src/json.hpp --gcov-options '\-lp' --gcov 'gcov-4.9'
|
||||
# env: COMPILER=g++-4.9
|
||||
#
|
||||
# - os: linux
|
||||
# compiler: gcc
|
||||
# before_install: echo -n | openssl s_client -connect scan.coverity.com:443 | sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p' | sudo tee -a /etc/ssl/certs/ca-certificates.crt
|
||||
# addons:
|
||||
# apt:
|
||||
# sources: ['ubuntu-toolchain-r-test']
|
||||
# packages: ['g++-5', 'valgrind']
|
||||
# coverity_scan:
|
||||
# project:
|
||||
# name: "nlohmann/json"
|
||||
# description: "Build submitted via Travis CI"
|
||||
# notification_email: niels.lohmann@gmail.com
|
||||
# build_command_prepend: "make clean ; sudo cp $(which g++-5) $(which g++)"
|
||||
# build_command: "make"
|
||||
# branch_pattern: coverity_scan
|
||||
# env: COMPILER=g++-5
|
||||
#
|
||||
@@ -1,54 +0,0 @@
|
||||
cmake_minimum_required(VERSION 3.0)
|
||||
|
||||
# define the project
|
||||
project(nlohmann_json VERSION 2.0.3 LANGUAGES CXX)
|
||||
|
||||
enable_testing()
|
||||
|
||||
option(BuildTests "Build the unit tests" ON)
|
||||
|
||||
# define project variables
|
||||
set(JSON_TARGET_NAME ${PROJECT_NAME})
|
||||
set(JSON_PACKAGE_NAME ${JSON_TARGET_NAME})
|
||||
set(JSON_TARGETS_FILENAME "${JSON_PACKAGE_NAME}Targets.cmake")
|
||||
set(JSON_CONFIG_FILENAME "${JSON_PACKAGE_NAME}Config.cmake")
|
||||
set(JSON_CONFIGVERSION_FILENAME "${JSON_PACKAGE_NAME}ConfigVersion.cmake")
|
||||
set(JSON_CONFIG_DESTINATION "cmake")
|
||||
set(JSON_INCLUDE_DESTINATION "include/nlohmann")
|
||||
|
||||
# create and configure the library target
|
||||
add_library(${JSON_TARGET_NAME} INTERFACE)
|
||||
target_include_directories(${JSON_TARGET_NAME} INTERFACE
|
||||
$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/src>
|
||||
$<INSTALL_INTERFACE:${JSON_INCLUDE_DESTINATION}>)
|
||||
|
||||
# create and configure the unit test target
|
||||
if (BuildTests)
|
||||
add_subdirectory(test)
|
||||
endif()
|
||||
|
||||
# generate a config and config version file for the package
|
||||
include(CMakePackageConfigHelpers)
|
||||
configure_package_config_file("cmake/config.cmake.in"
|
||||
"${CMAKE_CURRENT_BINARY_DIR}/${JSON_CONFIG_FILENAME}"
|
||||
INSTALL_DESTINATION ${JSON_CONFIG_DESTINATION})
|
||||
write_basic_package_version_file("${CMAKE_CURRENT_BINARY_DIR}/${JSON_CONFIGVERSION_FILENAME}"
|
||||
VERSION ${PROJECT_VERSION}
|
||||
COMPATIBILITY SameMajorVersion)
|
||||
|
||||
# export the library target and store build directory in package registry
|
||||
export(TARGETS ${JSON_TARGET_NAME}
|
||||
FILE "${CMAKE_CURRENT_BINARY_DIR}/${JSON_TARGETS_FILENAME}")
|
||||
export(PACKAGE ${JSON_PACKAGE_NAME})
|
||||
|
||||
# install library target and config files
|
||||
install(TARGETS ${JSON_TARGET_NAME}
|
||||
EXPORT ${JSON_PACKAGE_NAME})
|
||||
install(FILES "src/json.hpp"
|
||||
DESTINATION ${JSON_INCLUDE_DESTINATION})
|
||||
install(EXPORT ${JSON_PACKAGE_NAME}
|
||||
FILE ${JSON_TARGETS_FILENAME}
|
||||
DESTINATION ${JSON_CONFIG_DESTINATION})
|
||||
install(FILES "${CMAKE_CURRENT_BINARY_DIR}/${JSON_CONFIG_FILENAME}"
|
||||
"${CMAKE_CURRENT_BINARY_DIR}/${JSON_CONFIGVERSION_FILENAME}"
|
||||
DESTINATION ${JSON_CONFIG_DESTINATION})
|
||||
-248
@@ -1,248 +0,0 @@
|
||||
# Change Log
|
||||
All notable changes to this project will be documented in this file. This project adheres to [Semantic Versioning](http://semver.org/).
|
||||
|
||||
## [v2.0.3](https://github.com/nlohmann/json/releases/tag/v2.0.3) (2016-08-31)
|
||||
[Full Changelog](https://github.com/nlohmann/json/compare/v2.0.2...v2.0.3)
|
||||
|
||||
- Support for iterator-range parsing [\#290](https://github.com/nlohmann/json/issues/290)
|
||||
|
||||
- warning C4706: assignment within conditional expression [\#295](https://github.com/nlohmann/json/issues/295)
|
||||
- Horribly inconsistent behavior between const/non-const reference in operator \[\] \(\) [\#289](https://github.com/nlohmann/json/issues/289)
|
||||
|
||||
- unit-constructor1.cpp: Fix floating point truncation warning [\#300](https://github.com/nlohmann/json/pull/300) ([t-b](https://github.com/t-b))
|
||||
|
||||
## [v2.0.2](https://github.com/nlohmann/json/releases/tag/v2.0.2) (2016-07-31)
|
||||
[Full Changelog](https://github.com/nlohmann/json/compare/v2.0.1...v2.0.2)
|
||||
|
||||
- value\(\) does not work with \_json\_pointer types [\#283](https://github.com/nlohmann/json/issues/283)
|
||||
- Easy serialization of classes [\#280](https://github.com/nlohmann/json/issues/280)
|
||||
|
||||
- Build error for std::int64 [\#282](https://github.com/nlohmann/json/issues/282)
|
||||
|
||||
- hexify\(\) function emits conversion warning [\#270](https://github.com/nlohmann/json/issues/270)
|
||||
|
||||
- let the makefile choose the correct sed [\#279](https://github.com/nlohmann/json/pull/279) ([murinicanor](https://github.com/murinicanor))
|
||||
- Update hexify to use array lookup instead of ternary \(\#270\) [\#275](https://github.com/nlohmann/json/pull/275) ([dtoma](https://github.com/dtoma))
|
||||
|
||||
## [v2.0.1](https://github.com/nlohmann/json/releases/tag/v2.0.1) (2016-06-28)
|
||||
[Full Changelog](https://github.com/nlohmann/json/compare/v2.0.0...v2.0.1)
|
||||
|
||||
- dump\(\) performance degradation in v2 [\#272](https://github.com/nlohmann/json/issues/272)
|
||||
|
||||
- fixed a tiny typo [\#271](https://github.com/nlohmann/json/pull/271) ([thelostt](https://github.com/thelostt))
|
||||
|
||||
## [v2.0.0](https://github.com/nlohmann/json/releases/tag/v2.0.0) (2016-06-23)
|
||||
[Full Changelog](https://github.com/nlohmann/json/compare/v1.1.0...v2.0.0)
|
||||
|
||||
- concatenate objects [\#252](https://github.com/nlohmann/json/issues/252)
|
||||
- Unit test fails when doing a CMake out-of-tree build [\#241](https://github.com/nlohmann/json/issues/241)
|
||||
- Additional integration options [\#237](https://github.com/nlohmann/json/issues/237)
|
||||
- Can't use basic\_json::iterator as a base iterator for std::move\_iterator [\#233](https://github.com/nlohmann/json/issues/233)
|
||||
- Provide a FAQ [\#163](https://github.com/nlohmann/json/issues/163)
|
||||
- Create PULL\_REQUEST\_TEMPLATE.md [\#213](https://github.com/nlohmann/json/pull/213) ([whackashoe](https://github.com/whackashoe))
|
||||
- fixed noexcept; added constexpr [\#208](https://github.com/nlohmann/json/pull/208) ([nlohmann](https://github.com/nlohmann))
|
||||
- Add support for afl-fuzz testing [\#207](https://github.com/nlohmann/json/pull/207) ([mykter](https://github.com/mykter))
|
||||
- Issue \#178 - Extending support to full uint64\_t/int64\_t range and unsigned type \(updated\) [\#193](https://github.com/nlohmann/json/pull/193) ([twelsby](https://github.com/twelsby))
|
||||
|
||||
- json::diff generates incorrect patch when removing multiple array elements. [\#269](https://github.com/nlohmann/json/issues/269)
|
||||
- -Wconversion warning [\#259](https://github.com/nlohmann/json/issues/259)
|
||||
- Maybe a bug [\#258](https://github.com/nlohmann/json/issues/258)
|
||||
- -Wconversion warnings [\#239](https://github.com/nlohmann/json/issues/239)
|
||||
- ambiguous overload for 'push\_back' and 'operator+=' [\#235](https://github.com/nlohmann/json/issues/235)
|
||||
- Incorrect dumping of parsed numbers with exponents, but without decimal places [\#230](https://github.com/nlohmann/json/issues/230)
|
||||
- double values are serialized with commas as decimal points [\#228](https://github.com/nlohmann/json/issues/228)
|
||||
- Move semantics with std::initializer\_list [\#225](https://github.com/nlohmann/json/issues/225)
|
||||
- abort during getline in yyfill [\#223](https://github.com/nlohmann/json/issues/223)
|
||||
- Wrong link in the README.md [\#217](https://github.com/nlohmann/json/issues/217)
|
||||
- Small bugs in json.hpp \(get\_number\) and unit.cpp \(non-standard integer type test\) [\#199](https://github.com/nlohmann/json/issues/199)
|
||||
- GCC/clang floating point parsing bug in strtod\(\) [\#195](https://github.com/nlohmann/json/issues/195)
|
||||
- Bugs in miloyip/nativejson-benchmark: roundtrips [\#187](https://github.com/nlohmann/json/issues/187)
|
||||
- Floating point exceptions [\#181](https://github.com/nlohmann/json/issues/181)
|
||||
- In basic\_json::basic\_json\(const CompatibleArrayType& val\), the requirement of CompatibleArrayType is not strict enough. [\#174](https://github.com/nlohmann/json/issues/174)
|
||||
- Implicit assignment to std::string fails [\#144](https://github.com/nlohmann/json/issues/144)
|
||||
- Fix Issue \#265 [\#266](https://github.com/nlohmann/json/pull/266) ([06needhamt](https://github.com/06needhamt))
|
||||
- Issue \#195 - update Travis to Trusty due to gcc/clang strtod\(\) bug [\#196](https://github.com/nlohmann/json/pull/196) ([twelsby](https://github.com/twelsby))
|
||||
|
||||
- Compiler Errors With JSON.hpp [\#265](https://github.com/nlohmann/json/issues/265)
|
||||
- VS2015 compile fail [\#260](https://github.com/nlohmann/json/issues/260)
|
||||
- Error when using json in g++ [\#254](https://github.com/nlohmann/json/issues/254)
|
||||
- Update long-term goals [\#246](https://github.com/nlohmann/json/issues/246)
|
||||
- Error compile Android NDK error: 'strtof' is not a member of 'std' [\#219](https://github.com/nlohmann/json/issues/219)
|
||||
- Conflicting typedef of ssize\_t on Windows 32 bit when using Boost.Python [\#204](https://github.com/nlohmann/json/issues/204)
|
||||
- Integer conversion to unsigned [\#178](https://github.com/nlohmann/json/issues/178)
|
||||
|
||||
- Define CMake/CTest tests [\#247](https://github.com/nlohmann/json/pull/247) ([robertmrk](https://github.com/robertmrk))
|
||||
- Out of tree builds and a few other miscellaneous CMake cleanups. [\#242](https://github.com/nlohmann/json/pull/242) ([ChrisKitching](https://github.com/ChrisKitching))
|
||||
- Implement additional integration options [\#238](https://github.com/nlohmann/json/pull/238) ([robertmrk](https://github.com/robertmrk))
|
||||
- make serialization locale-independent [\#232](https://github.com/nlohmann/json/pull/232) ([nlohmann](https://github.com/nlohmann))
|
||||
- fixes \#223 by updating README.md [\#227](https://github.com/nlohmann/json/pull/227) ([kevin--](https://github.com/kevin--))
|
||||
- Use namespace std for int64\_t and uint64\_t [\#226](https://github.com/nlohmann/json/pull/226) ([lv-zheng](https://github.com/lv-zheng))
|
||||
- Added missing cerrno header to fix ERANGE compile error on android [\#222](https://github.com/nlohmann/json/pull/222) ([Teemperor](https://github.com/Teemperor))
|
||||
- Corrected readme [\#218](https://github.com/nlohmann/json/pull/218) ([Annihil](https://github.com/Annihil))
|
||||
- replaced ssize\_t occurrences with auto \(addresses \#204\) [\#205](https://github.com/nlohmann/json/pull/205) ([nlohmann](https://github.com/nlohmann))
|
||||
- Fixed issue \#199 - Small bugs in json.hpp \(get\_number\) and unit.cpp \(non-standard integer type test\) [\#200](https://github.com/nlohmann/json/pull/200) ([twelsby](https://github.com/twelsby))
|
||||
- Fix broken link [\#197](https://github.com/nlohmann/json/pull/197) ([vog](https://github.com/vog))
|
||||
|
||||
## [v1.1.0](https://github.com/nlohmann/json/releases/tag/v1.1.0) (2016-01-24)
|
||||
[Full Changelog](https://github.com/nlohmann/json/compare/v1.0.0...v1.1.0)
|
||||
|
||||
- JSON performance benchmark comparision [\#177](https://github.com/nlohmann/json/issues/177)
|
||||
- Since re2c is often ignored in pull requests, it may make sense to make a contributing.md file [\#175](https://github.com/nlohmann/json/issues/175)
|
||||
- Add assertions [\#168](https://github.com/nlohmann/json/issues/168)
|
||||
- range based for loop for objects [\#83](https://github.com/nlohmann/json/issues/83)
|
||||
- Implementation of get\_ref\(\) [\#184](https://github.com/nlohmann/json/pull/184) ([dariomt](https://github.com/dariomt))
|
||||
|
||||
- Small error in pull \#185 [\#194](https://github.com/nlohmann/json/issues/194)
|
||||
- Bugs in miloyip/nativejson-benchmark: floating-point parsing [\#186](https://github.com/nlohmann/json/issues/186)
|
||||
- Cannot index by key of type static constexpr const char\* [\#171](https://github.com/nlohmann/json/issues/171)
|
||||
- Fixed Issue \#171 - added two extra template overloads of operator\[\] for T\* arguments [\#189](https://github.com/nlohmann/json/pull/189) ([twelsby](https://github.com/twelsby))
|
||||
- Fixed issue \#167 - removed operator ValueType\(\) condition for VS2015 [\#188](https://github.com/nlohmann/json/pull/188) ([twelsby](https://github.com/twelsby))
|
||||
|
||||
- Floating point equality [\#185](https://github.com/nlohmann/json/issues/185)
|
||||
- Unused variables in catch [\#180](https://github.com/nlohmann/json/issues/180)
|
||||
- Typo in documentation [\#179](https://github.com/nlohmann/json/issues/179)
|
||||
- Android? [\#172](https://github.com/nlohmann/json/issues/172)
|
||||
- MSVC 2015 build fails when attempting to compare object\_t [\#167](https://github.com/nlohmann/json/issues/167)
|
||||
- Member detector is not portable [\#166](https://github.com/nlohmann/json/issues/166)
|
||||
- Unnecessary const\_cast [\#162](https://github.com/nlohmann/json/issues/162)
|
||||
- Consider submitting this to the Boost Library Incubator [\#66](https://github.com/nlohmann/json/issues/66)
|
||||
|
||||
- Fixed Issue \#186 - add strto\(f|d|ld\) overload wrappers, "-0.0" special case and FP trailing zero [\#191](https://github.com/nlohmann/json/pull/191) ([twelsby](https://github.com/twelsby))
|
||||
- Issue \#185 - remove approx\(\) and use \#pragma to kill warnings [\#190](https://github.com/nlohmann/json/pull/190) ([twelsby](https://github.com/twelsby))
|
||||
- Fixed some typos in CONTRIBUTING.md [\#182](https://github.com/nlohmann/json/pull/182) ([nibroc](https://github.com/nibroc))
|
||||
|
||||
## [v1.0.0](https://github.com/nlohmann/json/releases/tag/v1.0.0) (2015-12-27)
|
||||
[Full Changelog](https://github.com/nlohmann/json/compare/v1.0.0-rc1...v1.0.0)
|
||||
|
||||
- add key name to exception [\#160](https://github.com/nlohmann/json/issues/160)
|
||||
- prevent json.hpp from emitting compiler warnings [\#154](https://github.com/nlohmann/json/issues/154)
|
||||
- json::parse\(string\) does not check utf8 bom [\#152](https://github.com/nlohmann/json/issues/152)
|
||||
- unsigned 64bit values output as signed [\#151](https://github.com/nlohmann/json/issues/151)
|
||||
- Wish feature: json5 [\#150](https://github.com/nlohmann/json/issues/150)
|
||||
- overload of at\(\) with default value [\#133](https://github.com/nlohmann/json/issues/133)
|
||||
- Memory leak in face of exceptions [\#118](https://github.com/nlohmann/json/issues/118)
|
||||
- Find and Count for arrays [\#117](https://github.com/nlohmann/json/issues/117)
|
||||
- dynamically constructing an arbitrarily nested object [\#114](https://github.com/nlohmann/json/issues/114)
|
||||
- object field accessors [\#103](https://github.com/nlohmann/json/issues/103)
|
||||
- v8pp and json [\#95](https://github.com/nlohmann/json/issues/95)
|
||||
- Wishlist [\#65](https://github.com/nlohmann/json/issues/65)
|
||||
- Windows/Visual Studio \(through 2013\) is unsupported [\#62](https://github.com/nlohmann/json/issues/62)
|
||||
|
||||
- Bug in basic\_json::operator\[\] const overload [\#135](https://github.com/nlohmann/json/issues/135)
|
||||
- wrong enable\_if for const pointer \(instead of pointer-to-const\) [\#134](https://github.com/nlohmann/json/issues/134)
|
||||
- Visual Studio 14 Debug assertion failed [\#125](https://github.com/nlohmann/json/issues/125)
|
||||
- Compile error with g++ 4.9.3 cygwin 64-bit [\#112](https://github.com/nlohmann/json/issues/112)
|
||||
- error: unterminated raw string [\#109](https://github.com/nlohmann/json/issues/109)
|
||||
- \[clang-3.6.2\] string/sstream with number to json issue [\#107](https://github.com/nlohmann/json/issues/107)
|
||||
|
||||
- Getting member discarding qualifyer [\#159](https://github.com/nlohmann/json/issues/159)
|
||||
- basic\_json::iterator::value\(\) output includes quotes while basic\_json::iterator::key\(\) doesn't [\#158](https://github.com/nlohmann/json/issues/158)
|
||||
- Indexing `const basic\_json\<\>` with `const basic\_string\<char\>` [\#157](https://github.com/nlohmann/json/issues/157)
|
||||
- token\_type\_name\(token\_type t\): not all control paths return a value [\#156](https://github.com/nlohmann/json/issues/156)
|
||||
- Unable to compile on MSVC 2015 with SDL checking enabled: This function or variable may be unsafe. [\#149](https://github.com/nlohmann/json/issues/149)
|
||||
- dump\(\) convert strings encoded by utf-8 to shift-jis on windows 10. [\#147](https://github.com/nlohmann/json/issues/147)
|
||||
- Unable to get field names in a json object [\#145](https://github.com/nlohmann/json/issues/145)
|
||||
- json.hpp:5746:32: error: 'to\_string' is not a member of 'std' [\#136](https://github.com/nlohmann/json/issues/136)
|
||||
- Returning any data type [\#113](https://github.com/nlohmann/json/issues/113)
|
||||
- vector\<json\> copy constructor really weird [\#108](https://github.com/nlohmann/json/issues/108)
|
||||
- maintaining order of keys during iteration [\#106](https://github.com/nlohmann/json/issues/106)
|
||||
|
||||
- Replace sprintf with hex function, this fixes \#149 [\#153](https://github.com/nlohmann/json/pull/153) ([whackashoe](https://github.com/whackashoe))
|
||||
- Fix character skipping after a surrogate pair [\#146](https://github.com/nlohmann/json/pull/146) ([robertmrk](https://github.com/robertmrk))
|
||||
- Detect correctly pointer-to-const [\#137](https://github.com/nlohmann/json/pull/137) ([dariomt](https://github.com/dariomt))
|
||||
- disabled "CopyAssignable" test for MSVC in Debug mode, see \#125 [\#131](https://github.com/nlohmann/json/pull/131) ([dariomt](https://github.com/dariomt))
|
||||
- removed stream operator for iterator, resolution for \#125 [\#130](https://github.com/nlohmann/json/pull/130) ([dariomt](https://github.com/dariomt))
|
||||
- fixed typos in comments for examples [\#129](https://github.com/nlohmann/json/pull/129) ([dariomt](https://github.com/dariomt))
|
||||
- Remove superfluous inefficiency [\#126](https://github.com/nlohmann/json/pull/126) ([d-frey](https://github.com/d-frey))
|
||||
- remove invalid parameter '-stdlib=libc++' in CMakeLists.txt [\#124](https://github.com/nlohmann/json/pull/124) ([emvivre](https://github.com/emvivre))
|
||||
- exception-safe object creation, fixes \#118 [\#122](https://github.com/nlohmann/json/pull/122) ([d-frey](https://github.com/d-frey))
|
||||
- Fix small oversight. [\#121](https://github.com/nlohmann/json/pull/121) ([ColinH](https://github.com/ColinH))
|
||||
- Overload parse\(\) to accept an rvalue reference [\#120](https://github.com/nlohmann/json/pull/120) ([silverweed](https://github.com/silverweed))
|
||||
- Use the right variable name in doc string [\#115](https://github.com/nlohmann/json/pull/115) ([whoshuu](https://github.com/whoshuu))
|
||||
|
||||
## [v1.0.0-rc1](https://github.com/nlohmann/json/releases/tag/v1.0.0-rc1) (2015-07-26)
|
||||
- Adjust wording to JSON RFC [\#97](https://github.com/nlohmann/json/issues/97)
|
||||
- access by \(const\) reference [\#91](https://github.com/nlohmann/json/issues/91)
|
||||
- is\_integer and is\_float tests [\#90](https://github.com/nlohmann/json/issues/90)
|
||||
- MinGW have no std::to\_string [\#80](https://github.com/nlohmann/json/issues/80)
|
||||
- erase elements using iterators [\#57](https://github.com/nlohmann/json/issues/57)
|
||||
- Removing item from array [\#56](https://github.com/nlohmann/json/issues/56)
|
||||
- Serialize/Deserialize like PHP? [\#55](https://github.com/nlohmann/json/issues/55)
|
||||
- Document erase, count, and iterators key and value [\#52](https://github.com/nlohmann/json/issues/52)
|
||||
- Supported compilers [\#50](https://github.com/nlohmann/json/issues/50)
|
||||
- Use non-member begin/end [\#48](https://github.com/nlohmann/json/issues/48)
|
||||
- Erase key [\#47](https://github.com/nlohmann/json/issues/47)
|
||||
- Key iterator [\#46](https://github.com/nlohmann/json/issues/46)
|
||||
- Add count member function [\#45](https://github.com/nlohmann/json/issues/45)
|
||||
- Printing attribute names [\#39](https://github.com/nlohmann/json/issues/39)
|
||||
- Avoid using spaces when encoding without pretty print [\#31](https://github.com/nlohmann/json/issues/31)
|
||||
- Cannot encode long numbers [\#30](https://github.com/nlohmann/json/issues/30)
|
||||
- Creating an empty array [\#27](https://github.com/nlohmann/json/issues/27)
|
||||
- Custom allocator support [\#25](https://github.com/nlohmann/json/issues/25)
|
||||
- create a header-only version [\#16](https://github.com/nlohmann/json/issues/16)
|
||||
- Add to\_string overload for indentation [\#13](https://github.com/nlohmann/json/issues/13)
|
||||
- move code into namespace [\#9](https://github.com/nlohmann/json/issues/9)
|
||||
- free functions for explicit objects and arrays in initializer lists [\#8](https://github.com/nlohmann/json/issues/8)
|
||||
- Test case coverage [\#2](https://github.com/nlohmann/json/issues/2)
|
||||
- Parse streams incrementally. [\#40](https://github.com/nlohmann/json/pull/40) ([aburgh](https://github.com/aburgh))
|
||||
|
||||
- Binary string causes numbers to be dumped as hex [\#101](https://github.com/nlohmann/json/issues/101)
|
||||
- failed to iterator json object with reverse\_iterator [\#100](https://github.com/nlohmann/json/issues/100)
|
||||
- static analysis warnings [\#94](https://github.com/nlohmann/json/issues/94)
|
||||
- reverse\_iterator operator inheritance problem [\#93](https://github.com/nlohmann/json/issues/93)
|
||||
- Nonstandard integer type [\#89](https://github.com/nlohmann/json/issues/89)
|
||||
- lexer::get\_number return NAN [\#82](https://github.com/nlohmann/json/issues/82)
|
||||
- Handle infinity and NaN cases [\#70](https://github.com/nlohmann/json/issues/70)
|
||||
- errors in g++-4.8.1 [\#68](https://github.com/nlohmann/json/issues/68)
|
||||
- Double quotation mark is not parsed correctly [\#60](https://github.com/nlohmann/json/issues/60)
|
||||
- Do not use std::to\_string [\#51](https://github.com/nlohmann/json/issues/51)
|
||||
- Confused about iterating through json objects [\#49](https://github.com/nlohmann/json/issues/49)
|
||||
- Problem getting vector \(array\) of strings [\#44](https://github.com/nlohmann/json/issues/44)
|
||||
- Compilation error due to assuming that private=public [\#43](https://github.com/nlohmann/json/issues/43)
|
||||
- Use of deprecated implicit copy constructor [\#42](https://github.com/nlohmann/json/issues/42)
|
||||
- dumping a small number\_float just outputs 0.000000 [\#37](https://github.com/nlohmann/json/issues/37)
|
||||
- Avoid using spaces when encoding without pretty print [\#31](https://github.com/nlohmann/json/issues/31)
|
||||
- Cannot encode long numbers [\#30](https://github.com/nlohmann/json/issues/30)
|
||||
- segmentation fault when iterating over empty arrays/objects [\#28](https://github.com/nlohmann/json/issues/28)
|
||||
- Improper parsing of JSON string "\\" [\#17](https://github.com/nlohmann/json/issues/17)
|
||||
- Don't return "const values" [\#15](https://github.com/nlohmann/json/issues/15)
|
||||
- string parser does not recognize uncompliant strings [\#12](https://github.com/nlohmann/json/issues/12)
|
||||
- free functions for explicit objects and arrays in initializer lists [\#8](https://github.com/nlohmann/json/issues/8)
|
||||
- Runtime error in Travis job [\#1](https://github.com/nlohmann/json/issues/1)
|
||||
- Fix compilation of json\_unit with GCC 5 [\#59](https://github.com/nlohmann/json/pull/59) ([dkopecek](https://github.com/dkopecek))
|
||||
|
||||
- Finish documenting the public interface in Doxygen [\#102](https://github.com/nlohmann/json/issues/102)
|
||||
- 'noexcept' : unknown override specifier [\#99](https://github.com/nlohmann/json/issues/99)
|
||||
- Keys when iterating over objects [\#67](https://github.com/nlohmann/json/issues/67)
|
||||
- Complete brief documentation [\#61](https://github.com/nlohmann/json/issues/61)
|
||||
- Get coverage back to 100% [\#58](https://github.com/nlohmann/json/issues/58)
|
||||
- possible double-free in find function [\#11](https://github.com/nlohmann/json/issues/11)
|
||||
- UTF-8 encoding/deconding/testing [\#10](https://github.com/nlohmann/json/issues/10)
|
||||
- Add unit tests [\#4](https://github.com/nlohmann/json/issues/4)
|
||||
- Drop C++98 support [\#3](https://github.com/nlohmann/json/issues/3)
|
||||
|
||||
- Keyword 'inline' is useless when member functions are defined in headers [\#87](https://github.com/nlohmann/json/pull/87) ([ahamez](https://github.com/ahamez))
|
||||
- Remove useless typename [\#86](https://github.com/nlohmann/json/pull/86) ([ahamez](https://github.com/ahamez))
|
||||
- Avoid warning with Xcode's clang [\#85](https://github.com/nlohmann/json/pull/85) ([ahamez](https://github.com/ahamez))
|
||||
- Fix typos [\#73](https://github.com/nlohmann/json/pull/73) ([aqnouch](https://github.com/aqnouch))
|
||||
- Replace `default\_callback` function with `nullptr` and check for null… [\#72](https://github.com/nlohmann/json/pull/72) ([aburgh](https://github.com/aburgh))
|
||||
- support enum [\#71](https://github.com/nlohmann/json/pull/71) ([likebeta](https://github.com/likebeta))
|
||||
- Fix performance regression introduced with the parsing callback feature. [\#69](https://github.com/nlohmann/json/pull/69) ([aburgh](https://github.com/aburgh))
|
||||
- Improve the implementations of the comparission-operators [\#63](https://github.com/nlohmann/json/pull/63) ([Florianjw](https://github.com/Florianjw))
|
||||
- Feature/small float serialization [\#38](https://github.com/nlohmann/json/pull/38) ([jrandall](https://github.com/jrandall))
|
||||
- template version with re2c scanner [\#36](https://github.com/nlohmann/json/pull/36) ([nlohmann](https://github.com/nlohmann))
|
||||
- more descriptive documentation in example [\#33](https://github.com/nlohmann/json/pull/33) ([luxe](https://github.com/luxe))
|
||||
- Fix string conversion under Clang [\#26](https://github.com/nlohmann/json/pull/26) ([wancw](https://github.com/wancw))
|
||||
- Fixed dumping of strings [\#24](https://github.com/nlohmann/json/pull/24) ([Teemperor](https://github.com/Teemperor))
|
||||
- Added a remark to the readme that coverage is GCC only for now [\#23](https://github.com/nlohmann/json/pull/23) ([Teemperor](https://github.com/Teemperor))
|
||||
- Unicode escaping [\#22](https://github.com/nlohmann/json/pull/22) ([Teemperor](https://github.com/Teemperor))
|
||||
- Implemented the JSON spec for string parsing for everything but the \uXXXX escaping [\#21](https://github.com/nlohmann/json/pull/21) ([Teemperor](https://github.com/Teemperor))
|
||||
- add the std iterator typedefs to iterator and const\_iterator [\#19](https://github.com/nlohmann/json/pull/19) ([kirkshoop](https://github.com/kirkshoop))
|
||||
- Fixed escaped quotes [\#18](https://github.com/nlohmann/json/pull/18) ([Teemperor](https://github.com/Teemperor))
|
||||
- Fix double delete on std::bad\_alloc exception [\#14](https://github.com/nlohmann/json/pull/14) ([elliotgoodrich](https://github.com/elliotgoodrich))
|
||||
- Added CMake and lcov [\#6](https://github.com/nlohmann/json/pull/6) ([Teemperor](https://github.com/Teemperor))
|
||||
- Version 2.0 [\#5](https://github.com/nlohmann/json/pull/5) ([nlohmann](https://github.com/nlohmann))
|
||||
|
||||
|
||||
|
||||
\* *This Change Log was automatically generated by [github_changelog_generator](https://github.com/skywinder/Github-Changelog-Generator)*
|
||||
-22
@@ -1,22 +0,0 @@
|
||||
The library is licensed under the MIT License
|
||||
<http://opensource.org/licenses/MIT>:
|
||||
|
||||
Copyright (c) 2013-2016 Niels Lohmann
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy of
|
||||
this software and associated documentation files (the "Software"), to deal in
|
||||
the Software without restriction, including without limitation the rights to
|
||||
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
|
||||
of the Software, and to permit persons to whom the Software is furnished to do
|
||||
so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
@@ -1,111 +0,0 @@
|
||||
.PHONY: pretty clean ChangeLog.md
|
||||
|
||||
# used programs
|
||||
RE2C = re2c
|
||||
SED = sed
|
||||
|
||||
# main target
|
||||
all: json_unit
|
||||
|
||||
# clean up
|
||||
clean:
|
||||
rm -fr json_unit json_benchmarks fuzz fuzz-testing *.dSYM
|
||||
rm -fr benchmarks/files/numbers/*.json
|
||||
$(MAKE) clean -Cdoc
|
||||
$(MAKE) clean -Ctest
|
||||
|
||||
|
||||
##########################################################################
|
||||
# unit tests
|
||||
##########################################################################
|
||||
|
||||
# build unit tests
|
||||
json_unit:
|
||||
@$(MAKE) -C test
|
||||
|
||||
# run unit tests
|
||||
check: json_unit
|
||||
test/json_unit "*"
|
||||
|
||||
check-fast: json_unit
|
||||
test/json_unit
|
||||
|
||||
|
||||
##########################################################################
|
||||
# documentation tests
|
||||
##########################################################################
|
||||
|
||||
# compile example files and check output
|
||||
doctest:
|
||||
$(MAKE) check_output -C doc
|
||||
|
||||
|
||||
##########################################################################
|
||||
# fuzzing
|
||||
##########################################################################
|
||||
|
||||
# the overall fuzz testing target
|
||||
fuzz_testing:
|
||||
rm -fr fuzz-testing
|
||||
mkdir -p fuzz-testing fuzz-testing/testcases fuzz-testing/out
|
||||
$(MAKE) fuzz CXX=afl-clang++
|
||||
mv fuzz fuzz-testing
|
||||
find test/data/json_tests -size -5k -name *json | xargs -I{} cp "{}" fuzz-testing/testcases
|
||||
@echo "Execute: afl-fuzz -i fuzz-testing/testcases -o fuzz-testing/out fuzz-testing/fuzz"
|
||||
|
||||
# the fuzzer binary
|
||||
fuzz: test/src/fuzz.cpp src/json.hpp
|
||||
$(CXX) -std=c++11 $(CXXFLAGS) $(FLAGS) $(CPPFLAGS) -I src $< $(LDFLAGS) -o $@
|
||||
|
||||
|
||||
##########################################################################
|
||||
# static analyzer
|
||||
##########################################################################
|
||||
|
||||
# call cppcheck on the main header file
|
||||
cppcheck:
|
||||
cppcheck --enable=warning --inconclusive --force --std=c++11 src/json.hpp --error-exitcode=1
|
||||
|
||||
clang_sanitize: clean
|
||||
CXX=clang++ CXXFLAGS="-g -O2 -fsanitize=address -fsanitize=undefined -fno-omit-frame-pointer" $(MAKE)
|
||||
|
||||
##########################################################################
|
||||
# maintainer targets
|
||||
##########################################################################
|
||||
|
||||
# create scanner with re2c
|
||||
re2c: src/json.hpp.re2c
|
||||
$(RE2C) -W --bit-vectors --nested-ifs --no-debug-info $< | $(SED) '1d' > src/json.hpp
|
||||
|
||||
# pretty printer
|
||||
pretty:
|
||||
astyle --style=allman --indent=spaces=4 --indent-modifiers \
|
||||
--indent-switches --indent-preproc-block --indent-preproc-define \
|
||||
--indent-col1-comments --pad-oper --pad-header --align-pointer=type \
|
||||
--align-reference=type --add-brackets --convert-tabs --close-templates \
|
||||
--lineend=linux --preserve-date --suffix=none --formatted \
|
||||
src/json.hpp src/json.hpp.re2c test/src/*.cpp \
|
||||
benchmarks/benchmarks.cpp doc/examples/*.cpp
|
||||
|
||||
|
||||
##########################################################################
|
||||
# benchmarks
|
||||
##########################################################################
|
||||
|
||||
# benchmarks
|
||||
json_benchmarks: benchmarks/benchmarks.cpp benchmarks/benchpress.hpp benchmarks/cxxopts.hpp src/json.hpp
|
||||
cd benchmarks/files/numbers ; python generate.py
|
||||
$(CXX) -std=c++11 $(CXXFLAGS) -DNDEBUG -O3 -flto -I src -I benchmarks $< $(LDFLAGS) -o $@
|
||||
./json_benchmarks
|
||||
|
||||
|
||||
##########################################################################
|
||||
# changelog
|
||||
##########################################################################
|
||||
|
||||
NEXT_VERSION ?= "unreleased"
|
||||
|
||||
ChangeLog.md:
|
||||
github_changelog_generator -o ChangeLog.md --simple-list --release-url https://github.com/nlohmann/json/releases/tag/%s --future-release $(NEXT_VERSION)
|
||||
gsed -i 's|https://github.com/nlohmann/json/releases/tag/HEAD|https://github.com/nlohmann/json/tree/HEAD|' ChangeLog.md
|
||||
gsed -i '2i All notable changes to this project will be documented in this file. This project adheres to [Semantic Versioning](http://semver.org/).' ChangeLog.md
|
||||
@@ -1,518 +0,0 @@
|
||||
[](https://github.com/nlohmann/json/releases)
|
||||
|
||||
[](https://travis-ci.org/nlohmann/json)
|
||||
[](https://ci.appveyor.com/project/nlohmann/json)
|
||||
[](https://coveralls.io/r/nlohmann/json)
|
||||
[](http://melpon.org/wandbox/permlink/zkFPohcXJ2TFuAyq)
|
||||
[](http://nlohmann.github.io/json)
|
||||
[](https://raw.githubusercontent.com/nlohmann/json/master/LICENSE.MIT)
|
||||
[](https://github.com/nlohmann/json/releases)
|
||||
[](http://github.com/nlohmann/json/issues)
|
||||
[](https://bestpractices.coreinfrastructure.org/projects/289)
|
||||
|
||||
## Design goals
|
||||
|
||||
There are myriads of [JSON](http://json.org) libraries out there, and each may even have its reason to exist. Our class had these design goals:
|
||||
|
||||
- **Intuitive syntax**. In languages such as Python, JSON feels like a first class data type. We used all the operator magic of modern C++ to achieve the same feeling in your code. Check out the [examples below](#examples) and you know, what I mean.
|
||||
|
||||
- **Trivial integration**. Our whole code consists of a single header file [`json.hpp`](https://github.com/nlohmann/json/blob/develop/src/json.hpp). That's it. No library, no subproject, no dependencies, no complex build system. The class is written in vanilla C++11. All in all, everything should require no adjustment of your compiler flags or project settings.
|
||||
|
||||
- **Serious testing**. Our class is heavily [unit-tested](https://github.com/nlohmann/json/blob/master/test/src/unit.cpp) and covers [100%](https://coveralls.io/r/nlohmann/json) of the code, including all exceptional behavior. Furthermore, we checked with [Valgrind](http://valgrind.org) that there are no memory leaks. To maintain high quality, the project is following the [Core Infrastructure Initiative (CII) best practices](https://bestpractices.coreinfrastructure.org/projects/289).
|
||||
|
||||
Other aspects were not so important to us:
|
||||
|
||||
- **Memory efficiency**. Each JSON object has an overhead of one pointer (the maximal size of a union) and one enumeration element (1 byte). The default generalization uses the following C++ data types: `std::string` for strings, `int64_t`, `uint64_t` or `double` for numbers, `std::map` for objects, `std::vector` for arrays, and `bool` for Booleans. However, you can template the generalized class `basic_json` to your needs.
|
||||
|
||||
- **Speed**. We currently implement the parser as naive [recursive descent parser](http://en.wikipedia.org/wiki/Recursive_descent_parser) with hand coded string handling. It is fast enough, but a [LALR-parser](http://en.wikipedia.org/wiki/LALR_parser) may be even faster (but would consist of more files which makes the integration harder).
|
||||
|
||||
See the [contribution guidelines](https://github.com/nlohmann/json/blob/master/.github/CONTRIBUTING.md#please-dont) for more information.
|
||||
|
||||
|
||||
## Integration
|
||||
|
||||
The single required source, file `json.hpp` is in the `src` directory or [released here](https://github.com/nlohmann/json/releases). All you need to do is add
|
||||
|
||||
```cpp
|
||||
#include "json.hpp"
|
||||
|
||||
// for convenience
|
||||
using json = nlohmann::json;
|
||||
```
|
||||
|
||||
to the files you want to use JSON objects. That's it. Do not forget to set the necessary switches to enable C++11 (e.g., `-std=c++11` for GCC and Clang).
|
||||
|
||||
:beer: If you are using OS X and [Homebrew](http://brew.sh), just type `brew tap nlohmann/json` and `brew install nlohmann_json` and you're set. If you want the bleeding edge rather than the latest release, use `brew install nlohmann_json --HEAD`.
|
||||
|
||||
|
||||
## Examples
|
||||
|
||||
Here are some examples to give you an idea how to use the class.
|
||||
|
||||
Assume you want to create the JSON object
|
||||
|
||||
```json
|
||||
{
|
||||
"pi": 3.141,
|
||||
"happy": true,
|
||||
"name": "Niels",
|
||||
"nothing": null,
|
||||
"answer": {
|
||||
"everything": 42
|
||||
},
|
||||
"list": [1, 0, 2],
|
||||
"object": {
|
||||
"currency": "USD",
|
||||
"value": 42.99
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
With the JSON class, you could write:
|
||||
|
||||
```cpp
|
||||
// create an empty structure (null)
|
||||
json j;
|
||||
|
||||
// add a number that is stored as double (note the implicit conversion of j to an object)
|
||||
j["pi"] = 3.141;
|
||||
|
||||
// add a Boolean that is stored as bool
|
||||
j["happy"] = true;
|
||||
|
||||
// add a string that is 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 that is 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 you want to use. If you want to be explicit or express some edge cases, the functions `json::array` and `json::object` will help:
|
||||
|
||||
```cpp
|
||||
// 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"}), json::array({"value", 42.99}) };
|
||||
```
|
||||
|
||||
|
||||
### Serialization / Deserialization
|
||||
|
||||
You can create an object (deserialization) by appending `_json` to a string literal:
|
||||
|
||||
```cpp
|
||||
// create object from string literal
|
||||
json j = "{ \"happy\": true, \"pi\": 3.141 }"_json;
|
||||
|
||||
// or even nicer with a raw string literal
|
||||
auto j2 = R"(
|
||||
{
|
||||
"happy": true,
|
||||
"pi": 3.141
|
||||
}
|
||||
)"_json;
|
||||
|
||||
// or explicitly
|
||||
auto j3 = json::parse("{ \"happy\": true, \"pi\": 3.141 }");
|
||||
```
|
||||
|
||||
You can also get a string representation (serialize):
|
||||
|
||||
```cpp
|
||||
// explicit conversion to string
|
||||
std::string s = j.dump(); // {\"happy\":true,\"pi\":3.141}
|
||||
|
||||
// serialization with pretty printing
|
||||
// pass in the amount of spaces to indent
|
||||
std::cout << j.dump(4) << std::endl;
|
||||
// {
|
||||
// "happy": true,
|
||||
// "pi": 3.141
|
||||
// }
|
||||
```
|
||||
|
||||
You can also use streams to serialize and deserialize:
|
||||
|
||||
```cpp
|
||||
// deserialize from standard input
|
||||
json j;
|
||||
std::cin >> j;
|
||||
|
||||
// serialize to standard output
|
||||
std::cout << j;
|
||||
|
||||
// the setw manipulator was overloaded to set the indentation for pretty printing
|
||||
std::cout << std::setw(4) << j << std::endl;
|
||||
```
|
||||
|
||||
These operators work for any subclasses of `std::istream` or `std::ostream`.
|
||||
|
||||
Please note that setting the exception bit for `failbit` is inappropriate for this use case. It will result in program termination due to the `noexcept` specifier in use.
|
||||
|
||||
|
||||
### STL-like access
|
||||
|
||||
We designed the JSON class to behave just like an STL container. In fact, it satisfies the [**ReversibleContainer**](http://en.cppreference.com/w/cpp/concept/ReversibleContainer) requirement.
|
||||
|
||||
```cpp
|
||||
// create an array using push_back
|
||||
json j;
|
||||
j.push_back("foo");
|
||||
j.push_back(1);
|
||||
j.push_back(true);
|
||||
|
||||
// iterate the array
|
||||
for (json::iterator it = j.begin(); it != j.end(); ++it) {
|
||||
std::cout << *it << '\n';
|
||||
}
|
||||
|
||||
// range-based for
|
||||
for (auto& element : j) {
|
||||
std::cout << element << '\n';
|
||||
}
|
||||
|
||||
// getter/setter
|
||||
const std::string tmp = j[0];
|
||||
j[1] = 42;
|
||||
bool foo = j.at(2);
|
||||
|
||||
// other stuff
|
||||
j.size(); // 3 entries
|
||||
j.empty(); // false
|
||||
j.type(); // json::value_t::array
|
||||
j.clear(); // the array is empty again
|
||||
|
||||
// convenience type checkers
|
||||
j.is_null();
|
||||
j.is_boolean();
|
||||
j.is_number();
|
||||
j.is_object();
|
||||
j.is_array();
|
||||
j.is_string();
|
||||
|
||||
// comparison
|
||||
j == "[\"foo\", 1, true]"_json; // true
|
||||
|
||||
// create an object
|
||||
json o;
|
||||
o["foo"] = 23;
|
||||
o["bar"] = false;
|
||||
o["baz"] = 3.141;
|
||||
|
||||
// special iterator member functions for objects
|
||||
for (json::iterator it = o.begin(); it != o.end(); ++it) {
|
||||
std::cout << it.key() << " : " << it.value() << "\n";
|
||||
}
|
||||
|
||||
// find an entry
|
||||
if (o.find("foo") != o.end()) {
|
||||
// there is an entry with key "foo"
|
||||
}
|
||||
|
||||
// or simpler using count()
|
||||
int foo_present = o.count("foo"); // 1
|
||||
int fob_present = o.count("fob"); // 0
|
||||
|
||||
// delete an entry
|
||||
o.erase("foo");
|
||||
```
|
||||
|
||||
|
||||
### Conversion from STL containers
|
||||
|
||||
Any sequence container (`std::array`, `std::vector`, `std::deque`, `std::forward_list`, `std::list`) whose values can be used to construct JSON types (e.g., integers, floating point numbers, Booleans, string types, or again STL containers described in this section) can be used to create a JSON array. The same holds for similar associative containers (`std::set`, `std::multiset`, `std::unordered_set`, `std::unordered_multiset`), but in these cases the order of the elements of the array depends how the elements are ordered in the respective STL container.
|
||||
|
||||
```cpp
|
||||
std::vector<int> c_vector {1, 2, 3, 4};
|
||||
json j_vec(c_vector);
|
||||
// [1, 2, 3, 4]
|
||||
|
||||
std::deque<double> c_deque {1.2, 2.3, 3.4, 5.6};
|
||||
json j_deque(c_deque);
|
||||
// [1.2, 2.3, 3.4, 5.6]
|
||||
|
||||
std::list<bool> c_list {true, true, false, true};
|
||||
json j_list(c_list);
|
||||
// [true, true, false, true]
|
||||
|
||||
std::forward_list<int64_t> c_flist {12345678909876, 23456789098765, 34567890987654, 45678909876543};
|
||||
json j_flist(c_flist);
|
||||
// [12345678909876, 23456789098765, 34567890987654, 45678909876543]
|
||||
|
||||
std::array<unsigned long, 4> c_array {{1, 2, 3, 4}};
|
||||
json j_array(c_array);
|
||||
// [1, 2, 3, 4]
|
||||
|
||||
std::set<std::string> c_set {"one", "two", "three", "four", "one"};
|
||||
json j_set(c_set); // only one entry for "one" is used
|
||||
// ["four", "one", "three", "two"]
|
||||
|
||||
std::unordered_set<std::string> c_uset {"one", "two", "three", "four", "one"};
|
||||
json j_uset(c_uset); // only one entry for "one" is used
|
||||
// maybe ["two", "three", "four", "one"]
|
||||
|
||||
std::multiset<std::string> c_mset {"one", "two", "one", "four"};
|
||||
json j_mset(c_mset); // only one entry for "one" is used
|
||||
// maybe ["one", "two", "four"]
|
||||
|
||||
std::unordered_multiset<std::string> c_umset {"one", "two", "one", "four"};
|
||||
json j_umset(c_umset); // both entries for "one" are used
|
||||
// maybe ["one", "two", "one", "four"]
|
||||
```
|
||||
|
||||
Likewise, any associative key-value containers (`std::map`, `std::multimap`, `std::unordered_map`, `std::unordered_multimap`) whose keys can construct an `std::string` and whose values can be used to construct JSON types (see examples above) can be used to to create a JSON object. Note that in case of multimaps only one key is used in the JSON object and the value depends on the internal order of the STL container.
|
||||
|
||||
```cpp
|
||||
std::map<std::string, int> c_map { {"one", 1}, {"two", 2}, {"three", 3} };
|
||||
json j_map(c_map);
|
||||
// {"one": 1, "three": 3, "two": 2 }
|
||||
|
||||
std::unordered_map<const char*, double> c_umap { {"one", 1.2}, {"two", 2.3}, {"three", 3.4} };
|
||||
json j_umap(c_umap);
|
||||
// {"one": 1.2, "two": 2.3, "three": 3.4}
|
||||
|
||||
std::multimap<std::string, bool> c_mmap { {"one", true}, {"two", true}, {"three", false}, {"three", true} };
|
||||
json j_mmap(c_mmap); // only one entry for key "three" is used
|
||||
// maybe {"one": true, "two": true, "three": true}
|
||||
|
||||
std::unordered_multimap<std::string, bool> c_ummap { {"one", true}, {"two", true}, {"three", false}, {"three", true} };
|
||||
json j_ummap(c_ummap); // only one entry for key "three" is used
|
||||
// maybe {"one": true, "two": true, "three": true}
|
||||
```
|
||||
|
||||
### JSON Pointer and JSON Patch
|
||||
|
||||
The library supports **JSON Pointer** ([RFC 6901](https://tools.ietf.org/html/rfc6901)) as alternative means to address structured values. On top of this, **JSON Patch** ([RFC 6902](https://tools.ietf.org/html/rfc6902)) allows to describe differences between two JSON values - effectively allowing patch and diff operations known from Unix.
|
||||
|
||||
```cpp
|
||||
// a JSON value
|
||||
json j_original = R"({
|
||||
"baz": ["one", "two", "three"],
|
||||
"foo": "bar"
|
||||
})"_json;
|
||||
|
||||
// access members with a JSON pointer (RFC 6901)
|
||||
j_original["/baz/1"_json_pointer];
|
||||
// "two"
|
||||
|
||||
// a JSON patch (RFC 6902)
|
||||
json j_patch = R"([
|
||||
{ "op": "replace", "path": "/baz", "value": "boo" },
|
||||
{ "op": "add", "path": "/hello", "value": ["world"] },
|
||||
{ "op": "remove", "path": "/foo"}
|
||||
])"_json;
|
||||
|
||||
// apply the patch
|
||||
json j_result = j_original.patch(j_patch);
|
||||
// {
|
||||
// "baz": "boo",
|
||||
// "hello": ["world"]
|
||||
// }
|
||||
|
||||
// calculate a JSON patch from two JSON values
|
||||
json::diff(j_result, j_original);
|
||||
// [
|
||||
// { "op":" replace", "path": "/baz", "value": ["one", "two", "three"] },
|
||||
// { "op": "remove","path": "/hello" },
|
||||
// { "op": "add", "path": "/foo", "value": "bar" }
|
||||
// ]
|
||||
```
|
||||
|
||||
|
||||
### Implicit conversions
|
||||
|
||||
The type of the JSON object is determined automatically by the expression to store. Likewise, the stored value is implicitly converted.
|
||||
|
||||
```cpp
|
||||
// strings
|
||||
std::string s1 = "Hello, world!";
|
||||
json js = s1;
|
||||
std::string s2 = js;
|
||||
|
||||
// Booleans
|
||||
bool b1 = true;
|
||||
json jb = b1;
|
||||
bool b2 = jb;
|
||||
|
||||
// numbers
|
||||
int i = 42;
|
||||
json jn = i;
|
||||
double f = jn;
|
||||
|
||||
// etc.
|
||||
```
|
||||
|
||||
You can also explicitly ask for the value:
|
||||
|
||||
```cpp
|
||||
std::string vs = js.get<std::string>();
|
||||
bool vb = jb.get<bool>();
|
||||
int vi = jn.get<int>();
|
||||
|
||||
// etc.
|
||||
```
|
||||
|
||||
|
||||
## Supported compilers
|
||||
|
||||
Though it's 2016 already, the support for C++11 is still a bit sparse. Currently, the following compilers are known to work:
|
||||
|
||||
- GCC 4.9 - 6.0 (and possibly later)
|
||||
- Clang 3.4 - 3.9 (and possibly later)
|
||||
- Microsoft Visual C++ 2015 / Build Tools 14.0.25123.0 (and possibly later)
|
||||
|
||||
I would be happy to learn about other compilers/versions.
|
||||
|
||||
Please note:
|
||||
|
||||
- GCC 4.8 does not work because of two bugs ([55817](https://gcc.gnu.org/bugzilla/show_bug.cgi?id=55817) and [57824](https://gcc.gnu.org/bugzilla/show_bug.cgi?id=57824)) in the C++11 support. Note there is a [pull request](https://github.com/nlohmann/json/pull/212) to fix some of the issues.
|
||||
- Android defaults to using very old compilers and C++ libraries. To fix this, add the following to your `Application.mk`. This will switch to the LLVM C++ library, the Clang compiler, and enable C++11 and other features disabled by default.
|
||||
|
||||
```
|
||||
APP_STL := c++_shared
|
||||
NDK_TOOLCHAIN_VERSION := clang3.6
|
||||
APP_CPPFLAGS += -frtti -fexceptions
|
||||
```
|
||||
|
||||
The code compiles successfully with [Android NDK](https://developer.android.com/ndk/index.html?hl=ml), Revision 9 - 11 (and possibly later) and [CrystaX's Android NDK](https://www.crystax.net/en/android/ndk) version 10.
|
||||
|
||||
- For GCC running on MinGW or Android SDK, the error `'to_string' is not a member of 'std'` (or similarly, for `strtod`) may occur. Note this is not an issue with the code, but rather with the compiler itself. On Android, see above to build with a newer environment. For MinGW, please refer to [this site](http://tehsausage.com/mingw-to-string) and [this discussion](https://github.com/nlohmann/json/issues/136) for information on how to fix this bug. For Android NDK using `APP_STL := gnustl_static`, please refer to [this discussion](https://github.com/nlohmann/json/issues/219).
|
||||
|
||||
The following compilers are currently used in continuous integration at [Travis](https://travis-ci.org/nlohmann/json) and [AppVeyor](https://ci.appveyor.com/project/nlohmann/json):
|
||||
|
||||
| Compiler | Operating System | Version String |
|
||||
|-----------------|------------------------------|----------------|
|
||||
| GCC 4.9.3 | Ubuntu 14.04.4 LTS | g++-4.9 (Ubuntu 4.9.3-8ubuntu2~14.04) 4.9.3 |
|
||||
| GCC 5.3.0 | Ubuntu 14.04.4 LTS | g++-5 (Ubuntu 5.3.0-3ubuntu1~14.04) 5.3.0 20151204 |
|
||||
| GCC 6.1.1 | Ubuntu 14.04.4 LTS | g++-6 (Ubuntu 6.1.1-3ubuntu11~14.04.1) 6.1.1 20160511 |
|
||||
| Clang 3.6.0 | Ubuntu 14.04.4 LTS | clang version 3.6.0 (tags/RELEASE_360/final) |
|
||||
| Clang 3.6.1 | Ubuntu 14.04.4 LTS | clang version 3.6.1 (tags/RELEASE_361/final) |
|
||||
| Clang 3.6.2 | Ubuntu 14.04.4 LTS | clang version 3.6.2 (tags/RELEASE_362/final) |
|
||||
| Clang 3.7.0 | Ubuntu 14.04.4 LTS | clang version 3.7.0 (tags/RELEASE_370/final) |
|
||||
| Clang 3.7.1 | Ubuntu 14.04.4 LTS | clang version 3.7.1 (tags/RELEASE_371/final) |
|
||||
| Clang 3.8.0 | Ubuntu 14.04.4 LTS | clang version 3.8.0 (tags/RELEASE_380/final) |
|
||||
| Clang 3.8.1 | Ubuntu 14.04.4 LTS | clang version 3.8.1 (tags/RELEASE_381/final) |
|
||||
| Clang Xcode 6.1 | Darwin Kernel Version 13.4.0 (OSX 10.9.5) | Apple LLVM version 6.0 (clang-600.0.54) (based on LLVM 3.5svn) |
|
||||
| Clang Xcode 6.2 | Darwin Kernel Version 13.4.0 (OSX 10.9.5) | Apple LLVM version 6.0 (clang-600.0.57) (based on LLVM 3.5svn) |
|
||||
| Clang Xcode 6.3 | Darwin Kernel Version 14.3.0 (OSX 10.10.3) | Apple LLVM version 6.1.0 (clang-602.0.49) (based on LLVM 3.6.0svn) |
|
||||
| Clang Xcode 6.4 | Darwin Kernel Version 14.3.0 (OSX 10.10.3) | Apple LLVM version 6.1.0 (clang-602.0.53) (based on LLVM 3.6.0svn) |
|
||||
| Clang Xcode 7.1 | Darwin Kernel Version 14.5.0 (OSX 10.10.5) | Apple LLVM version 7.0.0 (clang-700.1.76) |
|
||||
| Clang Xcode 7.2 | Darwin Kernel Version 15.0.0 (OSX 10.10.5) | Apple LLVM version 7.0.2 (clang-700.1.81) |
|
||||
| Clang Xcode 7.3 | Darwin Kernel Version 15.0.0 (OSX 10.10.5) | Apple LLVM version 7.3.0 (clang-703.0.29) |
|
||||
| Clang Xcode 8.0 | Darwin Kernel Version 15.6.0 (OSX 10.11.6) | Apple LLVM version 8.0.0 (clang-800.0.38) |
|
||||
| Visual Studio 14 2015 | Windows Server 2012 R2 (x64) | Microsoft (R) Build Engine version 14.0.25123.0 |
|
||||
|
||||
|
||||
## License
|
||||
|
||||
<img align="right" src="http://opensource.org/trademarks/opensource/OSI-Approved-License-100x137.png">
|
||||
|
||||
The class is licensed under the [MIT License](http://opensource.org/licenses/MIT):
|
||||
|
||||
Copyright © 2013-2016 [Niels Lohmann](http://nlohmann.me)
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
|
||||
|
||||
## Thanks
|
||||
|
||||
I deeply appreciate the help of the following people.
|
||||
|
||||
- [Teemperor](https://github.com/Teemperor) implemented CMake support and lcov integration, realized escape and Unicode handling in the string parser, and fixed the JSON serialization.
|
||||
- [elliotgoodrich](https://github.com/elliotgoodrich) fixed an issue with double deletion in the iterator classes.
|
||||
- [kirkshoop](https://github.com/kirkshoop) made the iterators of the class composable to other libraries.
|
||||
- [wancw](https://github.com/wanwc) fixed a bug that hindered the class to compile with Clang.
|
||||
- Tomas Åblad found a bug in the iterator implementation.
|
||||
- [Joshua C. Randall](https://github.com/jrandall) fixed a bug in the floating-point serialization.
|
||||
- [Aaron Burghardt](https://github.com/aburgh) implemented code to parse streams incrementally. Furthermore, he greatly improved the parser class by allowing the definition of a filter function to discard undesired elements while parsing.
|
||||
- [Daniel Kopeček](https://github.com/dkopecek) fixed a bug in the compilation with GCC 5.0.
|
||||
- [Florian Weber](https://github.com/Florianjw) fixed a bug in and improved the performance of the comparison operators.
|
||||
- [Eric Cornelius](https://github.com/EricMCornelius) pointed out a bug in the handling with NaN and infinity values. He also improved the performance of the string escaping.
|
||||
- [易思龙](https://github.com/likebeta) implemented a conversion from anonymous enums.
|
||||
- [kepkin](https://github.com/kepkin) patiently pushed forward the support for Microsoft Visual studio.
|
||||
- [gregmarr](https://github.com/gregmarr) simplified the implementation of reverse iterators and helped with numerous hints and improvements.
|
||||
- [Caio Luppi](https://github.com/caiovlp) fixed a bug in the Unicode handling.
|
||||
- [dariomt](https://github.com/dariomt) fixed some typos in the examples.
|
||||
- [Daniel Frey](https://github.com/d-frey) cleaned up some pointers and implemented exception-safe memory allocation.
|
||||
- [Colin Hirsch](https://github.com/ColinH) took care of a small namespace issue.
|
||||
- [Huu Nguyen](https://github.com/whoshuu) correct a variable name in the documentation.
|
||||
- [Silverweed](https://github.com/silverweed) overloaded `parse()` to accept an rvalue reference.
|
||||
- [dariomt](https://github.com/dariomt) fixed a subtlety in MSVC type support and implemented the `get_ref()` function to get a reference to stored values.
|
||||
- [ZahlGraf](https://github.com/ZahlGraf) added a workaround that allows compilation using Android NDK.
|
||||
- [whackashoe](https://github.com/whackashoe) replaced a function that was marked as unsafe by Visual Studio.
|
||||
- [406345](https://github.com/406345) fixed two small warnings.
|
||||
- [Glen Fernandes](https://github.com/glenfe) noted a potential portability problem in the `has_mapped_type` function.
|
||||
- [Corbin Hughes](https://github.com/nibroc) fixed some typos in the contribution guidelines.
|
||||
- [twelsby](https://github.com/twelsby) fixed the array subscript operator, an issue that failed the MSVC build, and floating-point parsing/dumping. He further added support for unsigned integer numbers and implemented better roundtrip support for parsed numbers.
|
||||
- [Volker Diels-Grabsch](https://github.com/vog) fixed a link in the README file.
|
||||
- [msm-](https://github.com/msm-) added support for american fuzzy lop.
|
||||
- [Annihil](https://github.com/Annihil) fixed an example in the README file.
|
||||
- [Themercee](https://github.com/Themercee) noted a wrong URL in the README file.
|
||||
- [Lv Zheng](https://github.com/lv-zheng) fixed a namespace issue with `int64_t` and `uint64_t`.
|
||||
- [abc100m](https://github.com/abc100m) analyzed the issues with GCC 4.8 and proposed a [partial solution](https://github.com/nlohmann/json/pull/212).
|
||||
- [zewt](https://github.com/zewt) added useful notes to the README file about Android.
|
||||
- [Róbert Márki](https://github.com/robertmrk) added a fix to use move iterators and improved the integration via CMake.
|
||||
- [Chris Kitching](https://github.com/ChrisKitching) cleaned up the CMake files.
|
||||
- [Tom Needham](https://github.com/06needhamt) fixed a subtle bug with MSVC 2015 which was also proposed by [Michael K.](https://github.com/Epidal).
|
||||
- [Mário Feroldi](https://github.com/thelostt) fixed a small typo.
|
||||
- [duncanwerner](https://github.com/duncanwerner) found a really embarrassing performance regression in the 2.0.0 release.
|
||||
- [Damien](https://github.com/dtoma) fixed one of the last conversion warnings.
|
||||
- [Thomas Braun](https://github.com/t-b) fixed a warning in a test case.
|
||||
- [Théo DELRIEU](https://github.com/theodelrieu) patiently and constructively oversaw the long way toward [iterator-range parsing](https://github.com/nlohmann/json/issues/290).
|
||||
|
||||
Thanks a lot for helping out!
|
||||
|
||||
|
||||
## Notes
|
||||
|
||||
- The code contains numerous debug **assertions** which can be switched off by defining the preprocessor macro `NDEBUG`, see the [documentation of `assert`](http://en.cppreference.com/w/cpp/error/assert). In particular, note [`operator[]`](https://nlohmann.github.io/json/classnlohmann_1_1basic__json_a2e26bd0b0168abb61f67ad5bcd5b9fa1.html#a2e26bd0b0168abb61f67ad5bcd5b9fa1) implements **unchecked access** for const objects: If the given key is not present, the behavior is undefined (think of a dereferenced null pointer) and yields an [assertion failure](https://github.com/nlohmann/json/issues/289) if assertions are switched on. If you are not sure whether an element in an object exists, use checked access with the [`at()` function](https://nlohmann.github.io/json/classnlohmann_1_1basic__json_a674de1ee73e6bf4843fc5dc1351fb726.html#a674de1ee73e6bf4843fc5dc1351fb726).
|
||||
- As the exact type of a number is not defined in the [JSON specification](http://rfc7159.net/rfc7159), this library tries to choose the best fitting C++ number type automatically. As a result, the type `double` may be used to store numbers which may yield [**floating-point exceptions**](https://github.com/nlohmann/json/issues/181) in certain rare situations if floating-point exceptions have been unmasked in the calling code. These exceptions are not caused by the library and need to be fixed in the calling code, such as by re-masking the exceptions prior to calling library functions.
|
||||
|
||||
|
||||
## Execute unit tests
|
||||
|
||||
To compile and run the tests, you need to execute
|
||||
|
||||
```sh
|
||||
$ make check
|
||||
|
||||
===============================================================================
|
||||
All tests passed (8905158 assertions in 35 test cases)
|
||||
```
|
||||
|
||||
For more information, have a look at the file [.travis.yml](https://github.com/nlohmann/json/blob/master/.travis.yml).
|
||||
@@ -0,0 +1,35 @@
|
||||
# <small>nlohmann::</small>adl_serializer
|
||||
|
||||
```cpp
|
||||
template<typename, typename>
|
||||
struct adl_serializer;
|
||||
```
|
||||
|
||||
Serializer that uses ADL ([Argument-Dependent Lookup](https://en.cppreference.com/w/cpp/language/adl)) to choose
|
||||
`to_json`/`from_json` functions from the types' namespaces.
|
||||
|
||||
It is implemented similarly to
|
||||
|
||||
```cpp
|
||||
template<typename ValueType>
|
||||
struct adl_serializer {
|
||||
template<typename BasicJsonType>
|
||||
static void to_json(BasicJsonType& j, const T& value) {
|
||||
// calls the "to_json" method in T's namespace
|
||||
}
|
||||
|
||||
template<typename BasicJsonType>
|
||||
static void from_json(const BasicJsonType& j, T& value) {
|
||||
// same thing, but with the "from_json" method
|
||||
}
|
||||
};
|
||||
```
|
||||
|
||||
## Member functions
|
||||
|
||||
- [**from_json**](from_json.md) - convert a JSON value to any value type
|
||||
- [**to_json**](to_json.md) - convert any value type to a JSON value
|
||||
|
||||
## Version history
|
||||
|
||||
- Added in version 2.1.0.
|
||||
@@ -0,0 +1,74 @@
|
||||
# <small>nlohmann::adl_serializer::</small>from_json
|
||||
|
||||
```cpp
|
||||
// (1)
|
||||
template<typename BasicJsonType, typename TargetType = ValueType>
|
||||
static auto from_json(BasicJsonType && j, TargetType& val) noexcept(
|
||||
noexcept(::nlohmann::from_json(std::forward<BasicJsonType>(j), val)))
|
||||
-> decltype(::nlohmann::from_json(std::forward<BasicJsonType>(j), val), void())
|
||||
|
||||
// (2)
|
||||
template<typename BasicJsonType, typename TargetType = ValueType>
|
||||
static auto from_json(BasicJsonType && j) noexcept(
|
||||
noexcept(::nlohmann::from_json(std::forward<BasicJsonType>(j), detail::identity_tag<TargetType> {})))
|
||||
-> decltype(::nlohmann::from_json(std::forward<BasicJsonType>(j), detail::identity_tag<TargetType> {}))
|
||||
```
|
||||
|
||||
This function is usually called by the [`get()`](../basic_json/get.md) function of the [basic_json](../basic_json/index.md)
|
||||
class (either explicitly or via the conversion operators).
|
||||
|
||||
1. This function is chosen for default-constructible value types.
|
||||
2. This function is chosen for value types which are not default-constructible.
|
||||
|
||||
## Parameters
|
||||
|
||||
`j` (in)
|
||||
: JSON value to read from
|
||||
|
||||
`val` (out)
|
||||
: value to write to
|
||||
|
||||
## Return value
|
||||
|
||||
1. (none) -- the converted value is written to the output parameter `val`.
|
||||
2. the JSON value `j` converted to `TargetType`
|
||||
|
||||
## Examples
|
||||
|
||||
??? example "Example: (1) Default-constructible type"
|
||||
|
||||
The example below shows how a `from_json` function can be implemented for a user-defined type. This function is
|
||||
called by the `adl_serializer` when `get<ns::person>()` is called.
|
||||
|
||||
```cpp
|
||||
--8<-- "examples/from_json__default_constructible.cpp"
|
||||
```
|
||||
|
||||
Output:
|
||||
|
||||
```json
|
||||
--8<-- "examples/from_json__default_constructible.output"
|
||||
```
|
||||
|
||||
??? example "Example: (2) Non-default-constructible type"
|
||||
|
||||
The example below shows how a `from_json` is implemented as part of a specialization of the `adl_serializer` to
|
||||
realize the conversion of a non-default-constructible type.
|
||||
|
||||
```cpp
|
||||
--8<-- "examples/from_json__non_default_constructible.cpp"
|
||||
```
|
||||
|
||||
Output:
|
||||
|
||||
```json
|
||||
--8<-- "examples/from_json__non_default_constructible.output"
|
||||
```
|
||||
|
||||
## See also
|
||||
|
||||
- [to_json](to_json.md)
|
||||
|
||||
## Version history
|
||||
|
||||
- Added in version 2.1.0.
|
||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1,157 @@
|
||||
# nlohmann::adl_serializer::from_json
|
||||
|
||||
```
|
||||
// (1)
|
||||
template<typename BasicJsonType, typename TargetType = ValueType>
|
||||
static auto from_json(BasicJsonType && j, TargetType& val) noexcept(
|
||||
noexcept(::nlohmann::from_json(std::forward<BasicJsonType>(j), val)))
|
||||
-> decltype(::nlohmann::from_json(std::forward<BasicJsonType>(j), val), void())
|
||||
|
||||
// (2)
|
||||
template<typename BasicJsonType, typename TargetType = ValueType>
|
||||
static auto from_json(BasicJsonType && j) noexcept(
|
||||
noexcept(::nlohmann::from_json(std::forward<BasicJsonType>(j), detail::identity_tag<TargetType> {})))
|
||||
-> decltype(::nlohmann::from_json(std::forward<BasicJsonType>(j), detail::identity_tag<TargetType> {}))
|
||||
```
|
||||
|
||||
This function is usually called by the [`get()`](https://json.nlohmann.me/api/basic_json/get/index.md) function of the [basic_json](https://json.nlohmann.me/api/basic_json/index.md) class (either explicitly or via the conversion operators).
|
||||
|
||||
1. This function is chosen for default-constructible value types.
|
||||
1. This function is chosen for value types which are not default-constructible.
|
||||
|
||||
## Parameters
|
||||
|
||||
`j` (in) : JSON value to read from
|
||||
|
||||
`val` (out) : value to write to
|
||||
|
||||
## Return value
|
||||
|
||||
1. (none) -- the converted value is written to the output parameter `val`.
|
||||
1. the JSON value `j` converted to `TargetType`
|
||||
|
||||
## Examples
|
||||
|
||||
Example: (1) Default-constructible type
|
||||
|
||||
The example below shows how a `from_json` function can be implemented for a user-defined type. This function is called by the `adl_serializer` when `get<ns::person>()` is called.
|
||||
|
||||
```
|
||||
#include <iostream>
|
||||
#include <nlohmann/json.hpp>
|
||||
|
||||
using json = nlohmann::json;
|
||||
|
||||
namespace ns
|
||||
{
|
||||
// a simple struct to model a person
|
||||
struct person
|
||||
{
|
||||
std::string name;
|
||||
std::string address;
|
||||
int age;
|
||||
};
|
||||
} // namespace ns
|
||||
|
||||
namespace ns
|
||||
{
|
||||
void from_json(const json& j, person& p)
|
||||
{
|
||||
j.at("name").get_to(p.name);
|
||||
j.at("address").get_to(p.address);
|
||||
j.at("age").get_to(p.age);
|
||||
}
|
||||
} // namespace ns
|
||||
|
||||
int main()
|
||||
{
|
||||
json j;
|
||||
j["name"] = "Ned Flanders";
|
||||
j["address"] = "744 Evergreen Terrace";
|
||||
j["age"] = 60;
|
||||
|
||||
auto p = j.get<ns::person>();
|
||||
|
||||
std::cout << p.name << " (" << p.age << ") lives in " << p.address << std::endl;
|
||||
}
|
||||
```
|
||||
|
||||
Output:
|
||||
|
||||
```
|
||||
Ned Flanders (60) lives in 744 Evergreen Terrace
|
||||
```
|
||||
|
||||
Example: (2) Non-default-constructible type
|
||||
|
||||
The example below shows how a `from_json` is implemented as part of a specialization of the `adl_serializer` to realize the conversion of a non-default-constructible type.
|
||||
|
||||
```
|
||||
#include <iostream>
|
||||
#include <nlohmann/json.hpp>
|
||||
|
||||
using json = nlohmann::json;
|
||||
|
||||
namespace ns
|
||||
{
|
||||
// a simple struct to model a person (not default constructible)
|
||||
struct person
|
||||
{
|
||||
person(std::string n, std::string a, int aa)
|
||||
: name(std::move(n)), address(std::move(a)), age(aa)
|
||||
{}
|
||||
|
||||
std::string name;
|
||||
std::string address;
|
||||
int age;
|
||||
};
|
||||
} // namespace ns
|
||||
|
||||
namespace nlohmann
|
||||
{
|
||||
template <>
|
||||
struct adl_serializer<ns::person>
|
||||
{
|
||||
static ns::person from_json(const json& j)
|
||||
{
|
||||
return {j.at("name"), j.at("address"), j.at("age")};
|
||||
}
|
||||
|
||||
// Here's the catch! You must provide a to_json method! Otherwise, you
|
||||
// will not be able to convert person to json, since you fully
|
||||
// specialized adl_serializer on that type
|
||||
static void to_json(json& j, ns::person p)
|
||||
{
|
||||
j["name"] = p.name;
|
||||
j["address"] = p.address;
|
||||
j["age"] = p.age;
|
||||
}
|
||||
};
|
||||
} // namespace nlohmann
|
||||
|
||||
int main()
|
||||
{
|
||||
json j;
|
||||
j["name"] = "Ned Flanders";
|
||||
j["address"] = "744 Evergreen Terrace";
|
||||
j["age"] = 60;
|
||||
|
||||
auto p = j.get<ns::person>();
|
||||
|
||||
std::cout << p.name << " (" << p.age << ") lives in " << p.address << std::endl;
|
||||
}
|
||||
```
|
||||
|
||||
Output:
|
||||
|
||||
```
|
||||
Ned Flanders (60) lives in 744 Evergreen Terrace
|
||||
```
|
||||
|
||||
## See also
|
||||
|
||||
- [to_json](https://json.nlohmann.me/api/adl_serializer/to_json/index.md)
|
||||
|
||||
## Version history
|
||||
|
||||
- Added in version 2.1.0.
|
||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1,34 @@
|
||||
# nlohmann::adl_serializer
|
||||
|
||||
```
|
||||
template<typename, typename>
|
||||
struct adl_serializer;
|
||||
```
|
||||
|
||||
Serializer that uses ADL ([Argument-Dependent Lookup](https://en.cppreference.com/w/cpp/language/adl)) to choose `to_json`/`from_json` functions from the types' namespaces.
|
||||
|
||||
It is implemented similarly to
|
||||
|
||||
```
|
||||
template<typename ValueType>
|
||||
struct adl_serializer {
|
||||
template<typename BasicJsonType>
|
||||
static void to_json(BasicJsonType& j, const T& value) {
|
||||
// calls the "to_json" method in T's namespace
|
||||
}
|
||||
|
||||
template<typename BasicJsonType>
|
||||
static void from_json(const BasicJsonType& j, T& value) {
|
||||
// same thing, but with the "from_json" method
|
||||
}
|
||||
};
|
||||
```
|
||||
|
||||
## Member functions
|
||||
|
||||
- [**from_json**](https://json.nlohmann.me/api/adl_serializer/from_json/index.md) - convert a JSON value to any value type
|
||||
- [**to_json**](https://json.nlohmann.me/api/adl_serializer/to_json/index.md) - convert any value type to a JSON value
|
||||
|
||||
## Version history
|
||||
|
||||
- Added in version 2.1.0.
|
||||
@@ -0,0 +1,43 @@
|
||||
# <small>nlohmann::adl_serializer::</small>to_json
|
||||
|
||||
```cpp
|
||||
template<typename BasicJsonType, typename TargetType = ValueType>
|
||||
static auto to_json(BasicJsonType& j, TargetType && val) noexcept(
|
||||
noexcept(::nlohmann::to_json(j, std::forward<TargetType>(val))))
|
||||
-> decltype(::nlohmann::to_json(j, std::forward<TargetType>(val)), void())
|
||||
```
|
||||
|
||||
This function is usually called by the constructors of the [basic_json](../basic_json/index.md) class.
|
||||
|
||||
## Parameters
|
||||
|
||||
`j` (out)
|
||||
: JSON value to write to
|
||||
|
||||
`val` (in)
|
||||
: value to read from
|
||||
|
||||
## Examples
|
||||
|
||||
??? example
|
||||
|
||||
The example below shows how a `to_json` function can be implemented for a user-defined type. This function is called
|
||||
by the `adl_serializer` when the constructor `basic_json(ns::person)` is called.
|
||||
|
||||
```cpp
|
||||
--8<-- "examples/to_json.cpp"
|
||||
```
|
||||
|
||||
Output:
|
||||
|
||||
```json
|
||||
--8<-- "examples/to_json.output"
|
||||
```
|
||||
|
||||
## See also
|
||||
|
||||
- [from_json](from_json.md)
|
||||
|
||||
## Version history
|
||||
|
||||
- Added in version 2.1.0.
|
||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1,71 @@
|
||||
# nlohmann::adl_serializer::to_json
|
||||
|
||||
```
|
||||
template<typename BasicJsonType, typename TargetType = ValueType>
|
||||
static auto to_json(BasicJsonType& j, TargetType && val) noexcept(
|
||||
noexcept(::nlohmann::to_json(j, std::forward<TargetType>(val))))
|
||||
-> decltype(::nlohmann::to_json(j, std::forward<TargetType>(val)), void())
|
||||
```
|
||||
|
||||
This function is usually called by the constructors of the [basic_json](https://json.nlohmann.me/api/basic_json/index.md) class.
|
||||
|
||||
## Parameters
|
||||
|
||||
`j` (out) : JSON value to write to
|
||||
|
||||
`val` (in) : value to read from
|
||||
|
||||
## Examples
|
||||
|
||||
Example
|
||||
|
||||
The example below shows how a `to_json` function can be implemented for a user-defined type. This function is called by the `adl_serializer` when the constructor `basic_json(ns::person)` is called.
|
||||
|
||||
```
|
||||
#include <iostream>
|
||||
#include <nlohmann/json.hpp>
|
||||
|
||||
using json = nlohmann::json;
|
||||
|
||||
namespace ns
|
||||
{
|
||||
// a simple struct to model a person
|
||||
struct person
|
||||
{
|
||||
std::string name;
|
||||
std::string address;
|
||||
int age;
|
||||
};
|
||||
} // namespace ns
|
||||
|
||||
namespace ns
|
||||
{
|
||||
void to_json(json& j, const person& p)
|
||||
{
|
||||
j = json{ {"name", p.name}, {"address", p.address}, {"age", p.age} };
|
||||
}
|
||||
} // namespace ns
|
||||
|
||||
int main()
|
||||
{
|
||||
ns::person p = {"Ned Flanders", "744 Evergreen Terrace", 60};
|
||||
|
||||
json j = p;
|
||||
|
||||
std::cout << j << std::endl;
|
||||
}
|
||||
```
|
||||
|
||||
Output:
|
||||
|
||||
```
|
||||
{"address":"744 Evergreen Terrace","age":60,"name":"Ned Flanders"}
|
||||
```
|
||||
|
||||
## See also
|
||||
|
||||
- [from_json](https://json.nlohmann.me/api/adl_serializer/from_json/index.md)
|
||||
|
||||
## Version history
|
||||
|
||||
- Added in version 2.1.0.
|
||||
@@ -0,0 +1,338 @@
|
||||
# <small>nlohmann::</small>basic_json
|
||||
|
||||
<small>Defined in header `<nlohmann/json.hpp>`</small>
|
||||
|
||||
```cpp
|
||||
template<
|
||||
template<typename U, typename V, typename... Args> class ObjectType = std::map,
|
||||
template<typename U, typename... Args> class ArrayType = std::vector,
|
||||
class StringType = std::string,
|
||||
class BooleanType = bool,
|
||||
class NumberIntegerType = std::int64_t,
|
||||
class NumberUnsignedType = std::uint64_t,
|
||||
class NumberFloatType = double,
|
||||
template<typename U> class AllocatorType = std::allocator,
|
||||
template<typename T, typename SFINAE = void> class JSONSerializer = adl_serializer,
|
||||
class BinaryType = std::vector<std::uint8_t>,
|
||||
class CustomBaseClass = void
|
||||
>
|
||||
class basic_json;
|
||||
```
|
||||
|
||||
## Template parameters
|
||||
|
||||
| Template parameter | Description | Derived type |
|
||||
|----------------------|---------------------------------------------------------------------------|---------------------------------------------|
|
||||
| `ObjectType` | type for JSON objects | [`object_t`](object_t.md) |
|
||||
| `ArrayType` | type for JSON arrays | [`array_t`](array_t.md) |
|
||||
| `StringType` | type for JSON strings and object keys | [`string_t`](string_t.md) |
|
||||
| `BooleanType` | type for JSON booleans | [`boolean_t`](boolean_t.md) |
|
||||
| `NumberIntegerType` | type for JSON integer numbers | [`number_integer_t`](number_integer_t.md) |
|
||||
| `NumberUnsignedType` | type for JSON unsigned integer numbers | [`number_unsigned_t`](number_unsigned_t.md) |
|
||||
| `NumberFloatType` | type for JSON floating-point numbers | [`number_float_t`](number_float_t.md) |
|
||||
| `AllocatorType` | type of the allocator to use | |
|
||||
| `JSONSerializer` | the serializer to resolve internal calls to `to_json()` and `from_json()` | [`json_serializer`](json_serializer.md) |
|
||||
| `BinaryType` | type for binary arrays | [`binary_t`](binary_t.md) |
|
||||
| `CustomBaseClass` | extension point for user code | [`json_base_class_t`](json_base_class_t.md) |
|
||||
|
||||
## Specializations
|
||||
|
||||
- [**json**](../json.md) - default specialization
|
||||
- [**ordered_json**](../ordered_json.md) - a specialization that maintains the insertion order of object keys
|
||||
|
||||
## Iterator invalidation
|
||||
|
||||
All operations that add values to an **array** ([`push_back`](push_back.md) , [`operator+=`](operator+=.md),
|
||||
[`emplace_back`](emplace_back.md), [`insert`](insert.md), and [`operator[]`](operator%5B%5D.md) for a non-existing
|
||||
index) can yield a reallocation, in which case all iterators (including the [`end()`](end.md) iterator) and all
|
||||
references to the elements are invalidated.
|
||||
|
||||
For [`ordered_json`](../ordered_json.md), also all operations that add a value to an **object**
|
||||
([`push_back`](push_back.md), [`operator+=`](operator+=.md), [`emplace`](emplace.md), [`insert`](insert.md),
|
||||
[`update`](update.md), and [`operator[]`](operator%5B%5D.md) for a non-existing key) can yield a reallocation, in
|
||||
which case all iterators (including the [`end()`](end.md) iterator) and all references to the elements are invalidated.
|
||||
|
||||
## Requirements
|
||||
|
||||
The class satisfies the following concept requirements:
|
||||
|
||||
### Basic
|
||||
|
||||
- [DefaultConstructible](https://en.cppreference.com/w/cpp/named_req/DefaultConstructible): JSON values can be
|
||||
default-constructed. The result will be a JSON null value.
|
||||
- [MoveConstructible](https://en.cppreference.com/w/cpp/named_req/MoveConstructible): A JSON value can be constructed
|
||||
from an rvalue argument.
|
||||
- [CopyConstructible](https://en.cppreference.com/w/cpp/named_req/CopyConstructible): A JSON value can be
|
||||
copy-constructed from an lvalue expression.
|
||||
- [MoveAssignable](https://en.cppreference.com/w/cpp/named_req/MoveAssignable): A JSON value can be assigned from an
|
||||
rvalue argument.
|
||||
- [CopyAssignable](https://en.cppreference.com/w/cpp/named_req/CopyAssignable): A JSON value can be copy-assigned from
|
||||
an lvalue expression.
|
||||
- [Destructible](https://en.cppreference.com/w/cpp/named_req/Destructible): JSON values can be destructed.
|
||||
|
||||
### Layout
|
||||
|
||||
- [StandardLayoutType](https://en.cppreference.com/w/cpp/named_req/StandardLayoutType): JSON values have
|
||||
[standard layout](https://en.cppreference.com/w/cpp/language/data_members#Standard_layout): All non-static data
|
||||
members are private and standard layout types, the class has no virtual functions or (virtual) base classes.
|
||||
|
||||
### Library-wide
|
||||
|
||||
- [EqualityComparable](https://en.cppreference.com/w/cpp/named_req/EqualityComparable): JSON values can be compared with
|
||||
`==`, see [`operator==`](operator_eq.md).
|
||||
- [LessThanComparable](https://en.cppreference.com/w/cpp/named_req/LessThanComparable): JSON values can be compared with
|
||||
`<`, see [`operator<`](operator_le.md).
|
||||
- [Swappable](https://en.cppreference.com/w/cpp/named_req/Swappable): Any JSON lvalue or rvalue of can be swapped with
|
||||
any lvalue or rvalue of other compatible types, using unqualified function `swap`.
|
||||
- [NullablePointer](https://en.cppreference.com/w/cpp/named_req/NullablePointer): JSON values can be compared against
|
||||
`std::nullptr_t` objects which are used to model the `null` value.
|
||||
|
||||
### Container
|
||||
|
||||
- [Container](https://en.cppreference.com/w/cpp/named_req/Container): JSON values can be used like STL containers and
|
||||
provide iterator access.
|
||||
- [ReversibleContainer](https://en.cppreference.com/w/cpp/named_req/ReversibleContainer): JSON values can be used like
|
||||
STL containers and provide reverse iterator access.
|
||||
|
||||
## Member types
|
||||
|
||||
- [**adl_serializer**](../adl_serializer/index.md) - the default serializer
|
||||
- [**value_t**](value_t.md) - the JSON type enumeration
|
||||
- [**json_pointer**](../json_pointer/index.md) - JSON Pointer implementation
|
||||
- [**json_serializer**](json_serializer.md) - type of the serializer to for conversions from/to JSON
|
||||
- [**error_handler_t**](error_handler_t.md) - type to choose behavior on decoding errors
|
||||
- [**cbor_tag_handler_t**](cbor_tag_handler_t.md) - type to choose how to handle CBOR tags
|
||||
- **initializer_list_t** - type for initializer lists of `basic_json` values
|
||||
- [**input_format_t**](input_format_t.md) - type to choose the format to parse
|
||||
- [**json_sax_t**](../json_sax/index.md) - type for SAX events
|
||||
|
||||
### Exceptions
|
||||
|
||||
- [**exception**](exception.md) - general exception of the `basic_json` class
|
||||
- [**parse_error**](parse_error.md) - exception indicating a parse error
|
||||
- [**invalid_iterator**](invalid_iterator.md) - exception indicating errors with iterators
|
||||
- [**type_error**](type_error.md) - exception indicating executing a member function with a wrong type
|
||||
- [**out_of_range**](out_of_range.md) - exception indicating access out of the defined range
|
||||
- [**other_error**](other_error.md) - exception indicating other library errors
|
||||
|
||||
### Container types
|
||||
|
||||
| Type | Definition |
|
||||
|--------------------------|-----------------------------------------------------------------------------------------------------------|
|
||||
| `value_type` | `#!cpp basic_json` |
|
||||
| `reference` | `#!cpp value_type&` |
|
||||
| `const_reference` | `#!cpp const value_type&` |
|
||||
| `difference_type` | `#!cpp std::ptrdiff_t` |
|
||||
| `size_type` | `#!cpp std::size_t` |
|
||||
| `allocator_type` | `#!cpp AllocatorType<basic_json>` |
|
||||
| `pointer` | `#!cpp std::allocator_traits<allocator_type>::pointer` |
|
||||
| `const_pointer` | `#!cpp std::allocator_traits<allocator_type>::const_pointer` |
|
||||
| `iterator` | [LegacyBidirectionalIterator](https://en.cppreference.com/w/cpp/named_req/BidirectionalIterator) |
|
||||
| `const_iterator` | constant [LegacyBidirectionalIterator](https://en.cppreference.com/w/cpp/named_req/BidirectionalIterator) |
|
||||
| `reverse_iterator` | reverse iterator, derived from `iterator` |
|
||||
| `const_reverse_iterator` | reverse iterator, derived from `const_iterator` |
|
||||
| `iteration_proxy` | helper type for [`items`](items.md) function |
|
||||
|
||||
### JSON value data types
|
||||
|
||||
- [**array_t**](array_t.md) - type for arrays
|
||||
- [**binary_t**](binary_t.md) - type for binary arrays
|
||||
- [**boolean_t**](boolean_t.md) - type for booleans
|
||||
- [**default_object_comparator_t**](default_object_comparator_t.md) - default comparator for objects
|
||||
- [**number_float_t**](number_float_t.md) - type for numbers (floating-point)
|
||||
- [**number_integer_t**](number_integer_t.md) - type for numbers (integer)
|
||||
- [**number_unsigned_t**](number_unsigned_t.md) - type for numbers (unsigned)
|
||||
- [**object_comparator_t**](object_comparator_t.md) - comparator for objects
|
||||
- [**object_t**](object_t.md) - type for objects
|
||||
- [**string_t**](string_t.md) - type for strings
|
||||
|
||||
### Parser callback
|
||||
|
||||
- [**parse_event_t**](parse_event_t.md) - parser event types
|
||||
- [**parser_callback_t**](parser_callback_t.md) - per-element parser callback type
|
||||
|
||||
## Member functions
|
||||
|
||||
- [(constructor)](basic_json.md)
|
||||
- [(destructor)](~basic_json.md)
|
||||
- [**operator=**](operator=.md) - copy assignment
|
||||
- [**array**](array.md) (_static_) - explicitly create an array
|
||||
- [**binary**](binary.md) (_static_) - explicitly create a binary array
|
||||
- [**object**](object.md) (_static_) - explicitly create an object
|
||||
|
||||
### Object inspection
|
||||
|
||||
Functions to inspect the type of a JSON value.
|
||||
|
||||
- [**type**](type.md) - return the type of the JSON value
|
||||
- [**operator value_t**](operator_value_t.md) - return the type of the JSON value
|
||||
- [**type_name**](type_name.md) - return the type as string
|
||||
- [**is_primitive**](is_primitive.md) - return whether the type is primitive
|
||||
- [**is_structured**](is_structured.md) - return whether the type is structured
|
||||
- [**is_null**](is_null.md) - return whether the value is null
|
||||
- [**is_boolean**](is_boolean.md) - return whether the value is a boolean
|
||||
- [**is_number**](is_number.md) - return whether the value is a number
|
||||
- [**is_number_integer**](is_number_integer.md) - return whether the value is an integer number
|
||||
- [**is_number_unsigned**](is_number_unsigned.md) - return whether the value is an unsigned integer number
|
||||
- [**is_number_float**](is_number_float.md) - return whether the value is a floating-point number
|
||||
- [**is_object**](is_object.md) - return whether the value is an object
|
||||
- [**is_array**](is_array.md) - return whether the value is an array
|
||||
- [**is_string**](is_string.md) - return whether the value is a string
|
||||
- [**is_binary**](is_binary.md) - return whether the value is a binary array
|
||||
- [**is_discarded**](is_discarded.md) - return whether the value is discarded
|
||||
|
||||
Optional functions to access the [diagnostic positions](../macros/json_diagnostic_positions.md).
|
||||
|
||||
- [**start_pos**](start_pos.md) - return the start position of the value
|
||||
- [**end_pos**](end_pos.md) - return the one past the end position of the value
|
||||
|
||||
### Value access
|
||||
|
||||
Direct access to the stored value of a JSON value.
|
||||
|
||||
- [**get**](get.md) - get a value
|
||||
- [**get_to**](get_to.md) - get a value and write it to a destination
|
||||
- [**get_ptr**](get_ptr.md) - get a pointer value
|
||||
- [**get_ref**](get_ref.md) - get a reference value
|
||||
- [**operator ValueType**](operator_ValueType.md) - get a value
|
||||
- [**get_binary**](get_binary.md) - get a binary value
|
||||
|
||||
### Element access
|
||||
|
||||
Access to the JSON value
|
||||
|
||||
- [**at**](at.md) - access specified element with bounds checking
|
||||
- [**operator[]**](operator[].md) - access specified element
|
||||
- [**value**](value.md) - access specified object element with default value
|
||||
- [**front**](front.md) - access the first element
|
||||
- [**back**](back.md) - access the last element
|
||||
|
||||
### Lookup
|
||||
|
||||
- [**find**](find.md) - find an element in a JSON object
|
||||
- [**count**](count.md) - returns the number of occurrences of a key in a JSON object
|
||||
- [**contains**](contains.md) - check the existence of an element in a JSON object
|
||||
|
||||
### Iterators
|
||||
|
||||
- [**begin**](begin.md) - returns an iterator to the first element
|
||||
- [**cbegin**](cbegin.md) - returns a const iterator to the first element
|
||||
- [**end**](end.md) - returns an iterator to one past the last element
|
||||
- [**cend**](cend.md) - returns a const iterator to one past the last element
|
||||
- [**rbegin**](rbegin.md) - returns an iterator to the reverse-beginning
|
||||
- [**rend**](rend.md) - returns an iterator to the reverse-end
|
||||
- [**crbegin**](crbegin.md) - returns a const iterator to the reverse-beginning
|
||||
- [**crend**](crend.md) - returns a const iterator to the reverse-end
|
||||
- [**items**](items.md) - wrapper to access iterator member functions in range-based for
|
||||
|
||||
### Capacity
|
||||
|
||||
- [**empty**](empty.md) - checks whether the container is empty
|
||||
- [**size**](size.md) - returns the number of elements
|
||||
- [**max_size**](max_size.md) - returns the maximum possible number of elements
|
||||
|
||||
### Modifiers
|
||||
|
||||
- [**clear**](clear.md) - clears the contents
|
||||
- [**push_back**](push_back.md) - add a value to an array/object
|
||||
- [**operator+=**](operator+=.md) - add a value to an array/object
|
||||
- [**emplace_back**](emplace_back.md) - add a value to an array
|
||||
- [**emplace**](emplace.md) - add a value to an object if a key does not exist
|
||||
- [**erase**](erase.md) - remove elements
|
||||
- [**insert**](insert.md) - inserts elements
|
||||
- [**update**](update.md) - updates a JSON object from another object, overwriting existing keys
|
||||
- [**swap**](swap.md) - exchanges the values
|
||||
|
||||
### Lexicographical comparison operators
|
||||
|
||||
- [**operator==**](operator_eq.md) - comparison: equal
|
||||
- [**operator!=**](operator_ne.md) - comparison: not equal
|
||||
- [**operator<**](operator_lt.md) - comparison: less than
|
||||
- [**operator>**](operator_gt.md) - comparison: greater than
|
||||
- [**operator<=**](operator_le.md) - comparison: less than or equal
|
||||
- [**operator>=**](operator_ge.md) - comparison: greater than or equal
|
||||
- [**operator<=>**](operator_spaceship.md) - comparison: 3-way
|
||||
|
||||
### Serialization / Dumping
|
||||
|
||||
- [**dump**](dump.md) - serialization
|
||||
|
||||
### Deserialization / Parsing
|
||||
|
||||
- [**parse**](parse.md) (_static_) - deserialize from a compatible input
|
||||
- [**accept**](accept.md) (_static_) - check if the input is valid JSON
|
||||
- [**sax_parse**](sax_parse.md) (_static_) - generate SAX events
|
||||
|
||||
### JSON Pointer functions
|
||||
|
||||
- [**flatten**](flatten.md) - return flattened JSON value
|
||||
- [**unflatten**](unflatten.md) - unflatten a previously flattened JSON value
|
||||
|
||||
### JSON Patch functions
|
||||
|
||||
- [**patch**](patch.md) - applies a JSON patch
|
||||
- [**patch_inplace**](patch_inplace.md) - applies a JSON patch in place
|
||||
- [**diff**](diff.md) (_static_) - creates a diff as a JSON patch
|
||||
|
||||
### JSON Merge Patch functions
|
||||
|
||||
- [**merge_patch**](merge_patch.md) - applies a JSON Merge Patch
|
||||
|
||||
## Static functions
|
||||
|
||||
- [**meta**](meta.md) - returns version information on the library
|
||||
- [**get_allocator**](get_allocator.md) - returns the allocator associated with the container
|
||||
|
||||
### Binary formats
|
||||
|
||||
- [**from_bjdata**](from_bjdata.md) (_static_) - create a JSON value from an input in BJData format
|
||||
- [**from_bson**](from_bson.md) (_static_) - create a JSON value from an input in BSON format
|
||||
- [**from_cbor**](from_cbor.md) (_static_) - create a JSON value from an input in CBOR format
|
||||
- [**from_msgpack**](from_msgpack.md) (_static_) - create a JSON value from an input in MessagePack format
|
||||
- [**from_ubjson**](from_ubjson.md) (_static_) - create a JSON value from an input in UBJSON format
|
||||
- [**to_bjdata**](to_bjdata.md) (_static_) - create a BJData serialization of a given JSON value
|
||||
- [**to_bson**](to_bson.md) (_static_) - create a BSON serialization of a given JSON value
|
||||
- [**to_cbor**](to_cbor.md) (_static_) - create a CBOR serialization of a given JSON value
|
||||
- [**to_msgpack**](to_msgpack.md) (_static_) - create a MessagePack serialization of a given JSON value
|
||||
- [**to_ubjson**](to_ubjson.md) (_static_) - create a UBJSON serialization of a given JSON value
|
||||
|
||||
## Non-member functions
|
||||
|
||||
- [**operator<<(std::ostream&)**](../operator_ltlt.md) - serialize to stream
|
||||
- [**operator>>(std::istream&)**](../operator_gtgt.md) - deserialize from stream
|
||||
- [**to_string**](to_string.md) - user-defined `to_string` function for JSON values
|
||||
- [**format_as**](format_as.md) - user-defined `format_as` function for JSON values (fmt support)
|
||||
|
||||
## Literals
|
||||
|
||||
- [**operator""_json**](../operator_literal_json.md) - user-defined string literal for JSON values
|
||||
|
||||
## Helper classes
|
||||
|
||||
- [**std::formatter<basic_json>**](std_formatter.md) - make JSON values formattable with `std::format`
|
||||
- [**std::hash<basic_json>**](std_hash.md) - return a hash value for a JSON object
|
||||
- [**std::swap<basic_json>**](std_swap.md) - exchanges the values of two JSON objects
|
||||
|
||||
## Examples
|
||||
|
||||
??? example
|
||||
|
||||
The example shows how the library is used.
|
||||
|
||||
```cpp
|
||||
--8<-- "examples/README.cpp"
|
||||
```
|
||||
|
||||
Output:
|
||||
|
||||
```json
|
||||
--8<-- "examples/README.output"
|
||||
```
|
||||
|
||||
## See also
|
||||
|
||||
- [RFC 8259: The JavaScript Object Notation (JSON) Data Interchange Format](https://tools.ietf.org/html/rfc8259)
|
||||
|
||||
## Version history
|
||||
|
||||
- Added in version 1.0.0.
|
||||
@@ -0,0 +1,131 @@
|
||||
# <small>nlohmann::basic_json::</small>accept
|
||||
|
||||
```cpp
|
||||
// (1)
|
||||
template<typename InputType>
|
||||
static bool accept(InputType&& i,
|
||||
const bool ignore_comments = false,
|
||||
const bool ignore_trailing_commas = false);
|
||||
|
||||
// (2)
|
||||
template<typename IteratorType, typename SentinelType = IteratorType>
|
||||
static bool accept(IteratorType first, SentinelType last,
|
||||
const bool ignore_comments = false,
|
||||
const bool ignore_trailing_commas = false);
|
||||
```
|
||||
|
||||
Checks whether the input is valid JSON.
|
||||
|
||||
1. Reads from a compatible input.
|
||||
2. Reads from a pair of character iterators, or an iterator and a sentinel of a different type (C++20 ranges support)
|
||||
|
||||
The value_type of the iterator must be an integral type with a size of 1, 2, or 4 bytes, which will be interpreted
|
||||
respectively as UTF-8, UTF-16, and UTF-32. If `SentinelType` differs from `IteratorType`, it must be comparable to
|
||||
the iterator type with `operator!=`.
|
||||
|
||||
Unlike the [`parse()`](parse.md) function, this function neither throws an exception in case of invalid JSON input
|
||||
(i.e., a parse error) nor creates diagnostic information.
|
||||
|
||||
## Template parameters
|
||||
|
||||
`InputType`
|
||||
: A compatible input, for instance:
|
||||
|
||||
- an `std::istream` object
|
||||
- a `#!c FILE` pointer (throws if null)
|
||||
- a C-style array of characters
|
||||
- a pointer to a null-terminated string of single byte characters (throws if null)
|
||||
- a `std::string`
|
||||
- a container `obj` for which `begin(obj)` and `end(obj)` produce a valid pair of iterators
|
||||
(as found via ADL or member functions, with semantics compatible to `std::begin` and `std::end`)
|
||||
|
||||
`IteratorType`
|
||||
: a compatible iterator type, for instance.
|
||||
|
||||
- a pair of `std::string::iterator` or `std::vector<std::uint8_t>::iterator`
|
||||
- a pair of pointers such as `ptr` and `ptr + len`
|
||||
|
||||
`SentinelType`
|
||||
: defaults to `IteratorType`; may be a different type comparable to `IteratorType` via `operator!=`, for instance.
|
||||
|
||||
- a custom sentinel type for C++20 ranges
|
||||
- `std::default_sentinel_t`, when `IteratorType` is `std::counted_iterator`
|
||||
|
||||
## Parameters
|
||||
|
||||
`i` (in)
|
||||
: Input to parse from.
|
||||
|
||||
`ignore_comments` (in)
|
||||
: whether comments should be ignored and treated like whitespace (`#!cpp true`) or yield a parse error
|
||||
(`#!cpp false`); (optional, `#!cpp false` by default)
|
||||
|
||||
`ignore_trailing_commas` (in)
|
||||
: whether trailing commas in arrays or objects should be ignored and treated like whitespace (`#!cpp true`) or yield a parse error
|
||||
(`#!cpp false`); (optional, `#!cpp false` by default)
|
||||
|
||||
`first` (in)
|
||||
: iterator to the start of the character range
|
||||
|
||||
`last` (in)
|
||||
: iterator to the end of the character range, or a sentinel value that compares equal to the end iterator with `operator!=`
|
||||
|
||||
## Return value
|
||||
|
||||
Whether the input is valid JSON.
|
||||
|
||||
## Exception safety
|
||||
|
||||
Strong guarantee: if an exception is thrown, there are no changes in the JSON value.
|
||||
|
||||
## Exceptions
|
||||
|
||||
Throws [`parse_error.101`](../../home/exceptions.md#jsonexceptionparse_error101) in case of an empty input like a null `#!c FILE*` or `#!c char*` pointer.
|
||||
|
||||
## Complexity
|
||||
|
||||
Linear in the length of the input. The parser is a predictive LL(1) parser.
|
||||
|
||||
## Notes
|
||||
|
||||
A UTF-8 byte order mark is silently ignored.
|
||||
|
||||
## Examples
|
||||
|
||||
??? example
|
||||
|
||||
The example below demonstrates the `accept()` function reading from a string.
|
||||
|
||||
```cpp
|
||||
--8<-- "examples/accept__string.cpp"
|
||||
```
|
||||
|
||||
Output:
|
||||
|
||||
```json
|
||||
--8<-- "examples/accept__string.output"
|
||||
```
|
||||
|
||||
## See also
|
||||
|
||||
- [parse](parse.md) - deserialize from a compatible input
|
||||
- [sax_parse](sax_parse.md) - parse input using the SAX interface
|
||||
- [operator>>](../operator_gtgt.md) - deserialize from stream
|
||||
|
||||
## Version history
|
||||
|
||||
- Added in version 3.0.0.
|
||||
- Ignoring comments via `ignore_comments` added in version 3.9.0.
|
||||
- Changed [runtime assertion](../../features/assertions.md) in case of `FILE*` null pointers to exception in version 3.12.0.
|
||||
- Added `ignore_trailing_commas` in version 3.13.0.
|
||||
- Extended container support (1) to include types with lvalue-only ADL `begin`/`end` (matching `std::begin`/`std::end` semantics) in version 3.13.0.
|
||||
- Extended overload (2) to accept heterogeneous iterator+sentinel pairs (C++20 ranges support) in version 3.13.0.
|
||||
|
||||
!!! warning "Deprecation"
|
||||
|
||||
Overload (2) replaces calls to `accept` with a pair of iterators as their first parameter which has been
|
||||
deprecated in version 3.8.0. This overload will be removed in version 4.0.0. Please replace all calls like
|
||||
`#!cpp accept({ptr, ptr+len}, ...);` with `#!cpp accept(ptr, ptr+len, ...);`.
|
||||
|
||||
You should be warned by your compiler with a `-Wdeprecated-declarations` warning if you are using a deprecated
|
||||
function.
|
||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1,147 @@
|
||||
# nlohmann::basic_json::accept
|
||||
|
||||
```
|
||||
// (1)
|
||||
template<typename InputType>
|
||||
static bool accept(InputType&& i,
|
||||
const bool ignore_comments = false,
|
||||
const bool ignore_trailing_commas = false);
|
||||
|
||||
// (2)
|
||||
template<typename IteratorType, typename SentinelType = IteratorType>
|
||||
static bool accept(IteratorType first, SentinelType last,
|
||||
const bool ignore_comments = false,
|
||||
const bool ignore_trailing_commas = false);
|
||||
```
|
||||
|
||||
Checks whether the input is valid JSON.
|
||||
|
||||
1. Reads from a compatible input.
|
||||
|
||||
1. Reads from a pair of character iterators, or an iterator and a sentinel of a different type (C++20 ranges support)
|
||||
|
||||
The value_type of the iterator must be an integral type with a size of 1, 2, or 4 bytes, which will be interpreted respectively as UTF-8, UTF-16, and UTF-32. If `SentinelType` differs from `IteratorType`, it must be comparable to the iterator type with `operator!=`.
|
||||
|
||||
Unlike the [`parse()`](https://json.nlohmann.me/api/basic_json/parse/index.md) function, this function neither throws an exception in case of invalid JSON input (i.e., a parse error) nor creates diagnostic information.
|
||||
|
||||
## Template parameters
|
||||
|
||||
`InputType` : A compatible input, for instance:
|
||||
|
||||
```
|
||||
- an `std::istream` object
|
||||
- a `FILE` pointer (throws if null)
|
||||
- a C-style array of characters
|
||||
- a pointer to a null-terminated string of single byte characters (throws if null)
|
||||
- a `std::string`
|
||||
- a container `obj` for which `begin(obj)` and `end(obj)` produce a valid pair of iterators
|
||||
(as found via ADL or member functions, with semantics compatible to `std::begin` and `std::end`)
|
||||
```
|
||||
|
||||
`IteratorType` : a compatible iterator type, for instance.
|
||||
|
||||
```
|
||||
- a pair of `std::string::iterator` or `std::vector<std::uint8_t>::iterator`
|
||||
- a pair of pointers such as `ptr` and `ptr + len`
|
||||
```
|
||||
|
||||
`SentinelType` : defaults to `IteratorType`; may be a different type comparable to `IteratorType` via `operator!=`, for instance.
|
||||
|
||||
```
|
||||
- a custom sentinel type for C++20 ranges
|
||||
- `std::default_sentinel_t`, when `IteratorType` is `std::counted_iterator`
|
||||
```
|
||||
|
||||
## Parameters
|
||||
|
||||
`i` (in) : Input to parse from.
|
||||
|
||||
`ignore_comments` (in) : whether comments should be ignored and treated like whitespace (`true`) or yield a parse error (`false`); (optional, `false` by default)
|
||||
|
||||
`ignore_trailing_commas` (in) : whether trailing commas in arrays or objects should be ignored and treated like whitespace (`true`) or yield a parse error (`false`); (optional, `false` by default)
|
||||
|
||||
`first` (in) : iterator to the start of the character range
|
||||
|
||||
`last` (in) : iterator to the end of the character range, or a sentinel value that compares equal to the end iterator with `operator!=`
|
||||
|
||||
## Return value
|
||||
|
||||
Whether the input is valid JSON.
|
||||
|
||||
## Exception safety
|
||||
|
||||
Strong guarantee: if an exception is thrown, there are no changes in the JSON value.
|
||||
|
||||
## Exceptions
|
||||
|
||||
Throws [`parse_error.101`](https://json.nlohmann.me/home/exceptions/#jsonexceptionparse_error101) in case of an empty input like a null `FILE*` or `char*` pointer.
|
||||
|
||||
## Complexity
|
||||
|
||||
Linear in the length of the input. The parser is a predictive LL(1) parser.
|
||||
|
||||
## Notes
|
||||
|
||||
A UTF-8 byte order mark is silently ignored.
|
||||
|
||||
## Examples
|
||||
|
||||
Example
|
||||
|
||||
The example below demonstrates the `accept()` function reading from a string.
|
||||
|
||||
```
|
||||
#include <iostream>
|
||||
#include <iomanip>
|
||||
#include <nlohmann/json.hpp>
|
||||
|
||||
using json = nlohmann::json;
|
||||
|
||||
int main()
|
||||
{
|
||||
// a valid JSON text
|
||||
auto valid_text = R"(
|
||||
{
|
||||
"numbers": [1, 2, 3]
|
||||
}
|
||||
)";
|
||||
|
||||
// an invalid JSON text
|
||||
auto invalid_text = R"(
|
||||
{
|
||||
"strings": ["extra", "comma", ]
|
||||
}
|
||||
)";
|
||||
|
||||
std::cout << std::boolalpha
|
||||
<< json::accept(valid_text) << ' '
|
||||
<< json::accept(invalid_text) << '\n';
|
||||
}
|
||||
```
|
||||
|
||||
Output:
|
||||
|
||||
```
|
||||
true false
|
||||
```
|
||||
|
||||
## See also
|
||||
|
||||
- [parse](https://json.nlohmann.me/api/basic_json/parse/index.md) - deserialize from a compatible input
|
||||
- [sax_parse](https://json.nlohmann.me/api/basic_json/sax_parse/index.md) - parse input using the SAX interface
|
||||
- [operator>>](https://json.nlohmann.me/api/operator_gtgt/index.md) - deserialize from stream
|
||||
|
||||
## Version history
|
||||
|
||||
- Added in version 3.0.0.
|
||||
- Ignoring comments via `ignore_comments` added in version 3.9.0.
|
||||
- Changed [runtime assertion](https://json.nlohmann.me/features/assertions/index.md) in case of `FILE*` null pointers to exception in version 3.12.0.
|
||||
- Added `ignore_trailing_commas` in version 3.13.0.
|
||||
- Extended container support (1) to include types with lvalue-only ADL `begin`/`end` (matching `std::begin`/`std::end` semantics) in version 3.13.0.
|
||||
- Extended overload (2) to accept heterogeneous iterator+sentinel pairs (C++20 ranges support) in version 3.13.0.
|
||||
|
||||
Deprecation
|
||||
|
||||
Overload (2) replaces calls to `accept` with a pair of iterators as their first parameter which has been deprecated in version 3.8.0. This overload will be removed in version 4.0.0. Please replace all calls like `accept({ptr, ptr+len}, ...);` with `accept(ptr, ptr+len, ...);`.
|
||||
|
||||
You should be warned by your compiler with a `-Wdeprecated-declarations` warning if you are using a deprecated function.
|
||||
@@ -0,0 +1,61 @@
|
||||
# <small>nlohmann::basic_json::</small>array
|
||||
|
||||
```cpp
|
||||
static basic_json array(initializer_list_t init = {});
|
||||
```
|
||||
|
||||
Creates a JSON array value from a given initializer list. That is, given a list of values `a, b, c`, creates the JSON
|
||||
value `#!json [a, b, c]`. If the initializer list is empty, the empty array `#!json []` is created.
|
||||
|
||||
## Parameters
|
||||
|
||||
`init` (in)
|
||||
: initializer list with JSON values to create an array from (optional)
|
||||
|
||||
## Return value
|
||||
|
||||
JSON array value
|
||||
|
||||
## Exception safety
|
||||
|
||||
Strong guarantee: if an exception is thrown, there are no changes in the JSON value.
|
||||
|
||||
## Complexity
|
||||
|
||||
Linear in the size of `init`.
|
||||
|
||||
## Notes
|
||||
|
||||
This function is only needed to express two edge cases that cannot be realized with the initializer list constructor
|
||||
([`basic_json(initializer_list_t, bool, value_t)`](basic_json.md)). These cases are:
|
||||
|
||||
1. creating an array whose elements are all pairs whose first element is a string -- in this case, the initializer list
|
||||
constructor would create an object, taking the first elements as keys
|
||||
2. creating an empty array -- passing the empty initializer list to the initializer list constructor yields an empty
|
||||
object
|
||||
|
||||
## Examples
|
||||
|
||||
??? example
|
||||
|
||||
The following code shows an example for the `array` function.
|
||||
|
||||
```cpp
|
||||
--8<-- "examples/array.cpp"
|
||||
```
|
||||
|
||||
Output:
|
||||
|
||||
```json
|
||||
--8<-- "examples/array.output"
|
||||
```
|
||||
|
||||
## See also
|
||||
|
||||
- [`basic_json(initializer_list_t)`](basic_json.md) - create a JSON value from an initializer list
|
||||
- [`object`](object.md) - create a JSON object value from an initializer list
|
||||
- [Creating JSON values](../../features/creating_values.md) - the article on creating JSON values
|
||||
|
||||
## Version history
|
||||
|
||||
- Added in version 1.0.0.
|
||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1,77 @@
|
||||
# nlohmann::basic_json::array
|
||||
|
||||
```
|
||||
static basic_json array(initializer_list_t init = {});
|
||||
```
|
||||
|
||||
Creates a JSON array value from a given initializer list. That is, given a list of values `a, b, c`, creates the JSON value `[a, b, c]`. If the initializer list is empty, the empty array `[]` is created.
|
||||
|
||||
## Parameters
|
||||
|
||||
`init` (in) : initializer list with JSON values to create an array from (optional)
|
||||
|
||||
## Return value
|
||||
|
||||
JSON array value
|
||||
|
||||
## Exception safety
|
||||
|
||||
Strong guarantee: if an exception is thrown, there are no changes in the JSON value.
|
||||
|
||||
## Complexity
|
||||
|
||||
Linear in the size of `init`.
|
||||
|
||||
## Notes
|
||||
|
||||
This function is only needed to express two edge cases that cannot be realized with the initializer list constructor ([`basic_json(initializer_list_t, bool, value_t)`](https://json.nlohmann.me/api/basic_json/basic_json/index.md)). These cases are:
|
||||
|
||||
1. creating an array whose elements are all pairs whose first element is a string -- in this case, the initializer list constructor would create an object, taking the first elements as keys
|
||||
1. creating an empty array -- passing the empty initializer list to the initializer list constructor yields an empty object
|
||||
|
||||
## Examples
|
||||
|
||||
Example
|
||||
|
||||
The following code shows an example for the `array` function.
|
||||
|
||||
```
|
||||
#include <iostream>
|
||||
#include <nlohmann/json.hpp>
|
||||
|
||||
using json = nlohmann::json;
|
||||
|
||||
int main()
|
||||
{
|
||||
// create JSON arrays
|
||||
json j_no_init_list = json::array();
|
||||
json j_empty_init_list = json::array({});
|
||||
json j_nonempty_init_list = json::array({1, 2, 3, 4});
|
||||
json j_list_of_pairs = json::array({ {"one", 1}, {"two", 2} });
|
||||
|
||||
// serialize the JSON arrays
|
||||
std::cout << j_no_init_list << '\n';
|
||||
std::cout << j_empty_init_list << '\n';
|
||||
std::cout << j_nonempty_init_list << '\n';
|
||||
std::cout << j_list_of_pairs << '\n';
|
||||
}
|
||||
```
|
||||
|
||||
Output:
|
||||
|
||||
```
|
||||
[]
|
||||
[]
|
||||
[1,2,3,4]
|
||||
[["one",1],["two",2]]
|
||||
```
|
||||
|
||||
## See also
|
||||
|
||||
- [`basic_json(initializer_list_t)`](https://json.nlohmann.me/api/basic_json/basic_json/index.md) - create a JSON value from an initializer list
|
||||
- [`object`](https://json.nlohmann.me/api/basic_json/object/index.md) - create a JSON object value from an initializer list
|
||||
- [Creating JSON values](https://json.nlohmann.me/features/creating_values/index.md) - the article on creating JSON values
|
||||
|
||||
## Version history
|
||||
|
||||
- Added in version 1.0.0.
|
||||
@@ -0,0 +1,68 @@
|
||||
# <small>nlohmann::basic_json::</small>array_t
|
||||
|
||||
```cpp
|
||||
using array_t = ArrayType<basic_json, AllocatorType<basic_json>>;
|
||||
```
|
||||
|
||||
The type used to store JSON arrays.
|
||||
|
||||
[RFC 8259](https://tools.ietf.org/html/rfc8259) describes JSON arrays as follows:
|
||||
> An array is an ordered sequence of zero or more values.
|
||||
|
||||
To store objects in C++, a type is defined by the template parameters explained below.
|
||||
|
||||
## Template parameters
|
||||
|
||||
`ArrayType`
|
||||
: container type to store arrays (e.g., `std::vector` or `std::list`)
|
||||
|
||||
`AllocatorType`
|
||||
: the allocator to use for objects (e.g., `std::allocator`)
|
||||
|
||||
## Notes
|
||||
|
||||
#### Default type
|
||||
|
||||
With the default values for `ArrayType` (`std::vector`) and `AllocatorType` (`std::allocator`), the default value for
|
||||
`array_t` is:
|
||||
|
||||
```cpp
|
||||
std::vector<
|
||||
basic_json, // value_type
|
||||
std::allocator<basic_json> // allocator_type
|
||||
>
|
||||
```
|
||||
|
||||
#### Limits
|
||||
|
||||
[RFC 8259](https://tools.ietf.org/html/rfc8259) specifies:
|
||||
> An implementation may set limits on the maximum depth of nesting.
|
||||
|
||||
In this class, the array's limit of nesting is not explicitly constrained. However, a maximum depth of nesting may be
|
||||
introduced by the compiler or runtime environment. A theoretical limit can be queried by calling the
|
||||
[`max_size`](max_size.md) function of a JSON array.
|
||||
|
||||
#### Storage
|
||||
|
||||
Arrays are stored as pointers in a `basic_json` type. That is, for any access to array values, a pointer of type
|
||||
`#!cpp array_t*` must be dereferenced.
|
||||
|
||||
## Examples
|
||||
|
||||
??? example
|
||||
|
||||
The following code shows that `array_t` is by default, a typedef to `#!cpp std::vector<nlohmann::json>`.
|
||||
|
||||
```cpp
|
||||
--8<-- "examples/array_t.cpp"
|
||||
```
|
||||
|
||||
Output:
|
||||
|
||||
```json
|
||||
--8<-- "examples/array_t.output"
|
||||
```
|
||||
|
||||
## Version history
|
||||
|
||||
- Added in version 1.0.0.
|
||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1,73 @@
|
||||
# nlohmann::basic_json::array_t
|
||||
|
||||
```
|
||||
using array_t = ArrayType<basic_json, AllocatorType<basic_json>>;
|
||||
```
|
||||
|
||||
The type used to store JSON arrays.
|
||||
|
||||
[RFC 8259](https://tools.ietf.org/html/rfc8259) describes JSON arrays as follows:
|
||||
|
||||
> An array is an ordered sequence of zero or more values.
|
||||
|
||||
To store objects in C++, a type is defined by the template parameters explained below.
|
||||
|
||||
## Template parameters
|
||||
|
||||
`ArrayType` : container type to store arrays (e.g., `std::vector` or `std::list`)
|
||||
|
||||
`AllocatorType` : the allocator to use for objects (e.g., `std::allocator`)
|
||||
|
||||
## Notes
|
||||
|
||||
#### Default type
|
||||
|
||||
With the default values for `ArrayType` (`std::vector`) and `AllocatorType` (`std::allocator`), the default value for `array_t` is:
|
||||
|
||||
```
|
||||
std::vector<
|
||||
basic_json, // value_type
|
||||
std::allocator<basic_json> // allocator_type
|
||||
>
|
||||
```
|
||||
|
||||
#### Limits
|
||||
|
||||
[RFC 8259](https://tools.ietf.org/html/rfc8259) specifies:
|
||||
|
||||
> An implementation may set limits on the maximum depth of nesting.
|
||||
|
||||
In this class, the array's limit of nesting is not explicitly constrained. However, a maximum depth of nesting may be introduced by the compiler or runtime environment. A theoretical limit can be queried by calling the [`max_size`](https://json.nlohmann.me/api/basic_json/max_size/index.md) function of a JSON array.
|
||||
|
||||
#### Storage
|
||||
|
||||
Arrays are stored as pointers in a `basic_json` type. That is, for any access to array values, a pointer of type `array_t*` must be dereferenced.
|
||||
|
||||
## Examples
|
||||
|
||||
Example
|
||||
|
||||
The following code shows that `array_t` is by default, a typedef to `std::vector<nlohmann::json>`.
|
||||
|
||||
```
|
||||
#include <iostream>
|
||||
#include <iomanip>
|
||||
#include <nlohmann/json.hpp>
|
||||
|
||||
using json = nlohmann::json;
|
||||
|
||||
int main()
|
||||
{
|
||||
std::cout << std::boolalpha << std::is_same<std::vector<json>, json::array_t>::value << std::endl;
|
||||
}
|
||||
```
|
||||
|
||||
Output:
|
||||
|
||||
```
|
||||
true
|
||||
```
|
||||
|
||||
## Version history
|
||||
|
||||
- Added in version 1.0.0.
|
||||
@@ -0,0 +1,228 @@
|
||||
# <small>nlohmann::basic_json::</small>at
|
||||
|
||||
```cpp
|
||||
// (1)
|
||||
reference at(size_type idx);
|
||||
const_reference at(size_type idx) const;
|
||||
|
||||
// (2)
|
||||
reference at(const typename object_t::key_type& key);
|
||||
const_reference at(const typename object_t::key_type& key) const;
|
||||
|
||||
// (3)
|
||||
template<typename KeyType>
|
||||
reference at(KeyType&& key);
|
||||
template<typename KeyType>
|
||||
const_reference at(KeyType&& key) const;
|
||||
|
||||
// (4)
|
||||
reference at(const json_pointer& ptr);
|
||||
const_reference at(const json_pointer& ptr) const;
|
||||
```
|
||||
|
||||
1. Returns a reference to the array element at specified location `idx`, with bounds checking.
|
||||
2. Returns a reference to the object element with specified key `key`, with bounds checking.
|
||||
3. See 2. This overload is only available if `KeyType` is comparable with `#!cpp typename object_t::key_type` and
|
||||
`#!cpp typename object_comparator_t::is_transparent` denotes a type.
|
||||
4. Returns a reference to the element at specified JSON pointer `ptr`, with bounds checking.
|
||||
|
||||
## Template parameters
|
||||
|
||||
`KeyType`
|
||||
: A type for an object key other than [`json_pointer`](../json_pointer/index.md) that is comparable with
|
||||
[`string_t`](string_t.md) using [`object_comparator_t`](object_comparator_t.md).
|
||||
This can also be a string view (C++17).
|
||||
|
||||
## Parameters
|
||||
|
||||
`idx` (in)
|
||||
: index of the element to access
|
||||
|
||||
`key` (in)
|
||||
: object key of the elements to access
|
||||
|
||||
`ptr` (in)
|
||||
: JSON pointer to the desired element
|
||||
|
||||
## Return value
|
||||
|
||||
1. reference to the element at index `idx`
|
||||
2. reference to the element at key `key`
|
||||
3. reference to the element at key `key`
|
||||
4. reference to the element pointed to by `ptr`
|
||||
|
||||
## Exception safety
|
||||
|
||||
Strong exception safety: if an exception occurs, the original value stays intact.
|
||||
|
||||
## Exceptions
|
||||
|
||||
1. The function can throw the following exceptions:
|
||||
- Throws [`type_error.304`](../../home/exceptions.md#jsonexceptiontype_error304) if the JSON value is not an array;
|
||||
in this case, calling `at` with an index makes no sense. See the example below.
|
||||
- Throws [`out_of_range.401`](../../home/exceptions.md#jsonexceptionout_of_range401) if the index `idx` is out of
|
||||
range of the array; that is, `idx >= size()`. See the example below.
|
||||
2. The function can throw the following exceptions:
|
||||
- Throws [`type_error.304`](../../home/exceptions.md#jsonexceptiontype_error304) if the JSON value is not an object;
|
||||
in this case, calling `at` with a key makes no sense. See the example below.
|
||||
- Throws [`out_of_range.403`](../../home/exceptions.md#jsonexceptionout_of_range403) if the key `key` is not
|
||||
stored in the object; that is, `find(key) == end()`. See the example below.
|
||||
3. See 2.
|
||||
4. The function can throw the following exceptions:
|
||||
- Throws [`parse_error.106`](../../home/exceptions.md#jsonexceptionparse_error106) if an array index in the passed
|
||||
JSON pointer `ptr` begins with '0'. See the example below.
|
||||
- Throws [`parse_error.109`](../../home/exceptions.md#jsonexceptionparse_error109) if an array index in the passed
|
||||
JSON pointer `ptr` is not a number. See the example below.
|
||||
- Throws [`out_of_range.401`](../../home/exceptions.md#jsonexceptionout_of_range401) if an array index in the passed
|
||||
JSON pointer `ptr` is out of range. See the example below.
|
||||
- Throws [`out_of_range.402`](../../home/exceptions.md#jsonexceptionout_of_range402) if the array index '-' is used
|
||||
in the passed JSON pointer `ptr`. As `at` provides checked access (and no elements are implicitly inserted), the
|
||||
index '-' is always invalid. See the example below.
|
||||
- Throws [`out_of_range.403`](../../home/exceptions.md#jsonexceptionout_of_range403) if the JSON pointer describes a
|
||||
key of an object which cannot be found. See the example below.
|
||||
- Throws [`out_of_range.404`](../../home/exceptions.md#jsonexceptionout_of_range404) if the JSON pointer `ptr` can
|
||||
not be resolved. See the example below.
|
||||
- Throws [`out_of_range.410`](../../home/exceptions.md#jsonexceptionout_of_range410) if an array index in the passed
|
||||
JSON pointer `ptr` exceeds the range of `size_type` (e.g., on 32-bit platforms).
|
||||
|
||||
## Complexity
|
||||
|
||||
1. Constant.
|
||||
2. Logarithmic in the size of the container.
|
||||
3. Logarithmic in the size of the container.
|
||||
4. Logarithmic in the size of the container.
|
||||
|
||||
## Examples
|
||||
|
||||
??? example "Example: (1) access specified array element with bounds checking"
|
||||
|
||||
The example below shows how array elements can be read and written using `at()`. It also demonstrates the different
|
||||
exceptions that can be thrown.
|
||||
|
||||
```cpp
|
||||
--8<-- "examples/at__size_type.cpp"
|
||||
```
|
||||
|
||||
Output:
|
||||
|
||||
```json
|
||||
--8<-- "examples/at__size_type.output"
|
||||
```
|
||||
|
||||
??? example "Example: (1) access specified array element with bounds checking"
|
||||
|
||||
The example below shows how array elements can be read using `at()`. It also demonstrates the different exceptions
|
||||
that can be thrown.
|
||||
|
||||
```cpp
|
||||
--8<-- "examples/at__size_type_const.cpp"
|
||||
```
|
||||
|
||||
Output:
|
||||
|
||||
```json
|
||||
--8<-- "examples/at__size_type_const.output"
|
||||
```
|
||||
|
||||
??? example "Example: (2) access specified object element with bounds checking"
|
||||
|
||||
The example below shows how object elements can be read and written using `at()`. It also demonstrates the different
|
||||
exceptions that can be thrown.
|
||||
|
||||
```cpp
|
||||
--8<-- "examples/at__object_t_key_type.cpp"
|
||||
```
|
||||
|
||||
Output:
|
||||
|
||||
```json
|
||||
--8<-- "examples/at__object_t_key_type.output"
|
||||
```
|
||||
|
||||
??? example "Example: (2) access specified object element with bounds checking"
|
||||
|
||||
The example below shows how object elements can be read using `at()`. It also demonstrates the different exceptions
|
||||
that can be thrown.
|
||||
|
||||
```cpp
|
||||
--8<-- "examples/at__object_t_key_type_const.cpp"
|
||||
```
|
||||
|
||||
Output:
|
||||
|
||||
```json
|
||||
--8<-- "examples/at__object_t_key_type_const.output"
|
||||
```
|
||||
|
||||
??? example "Example: (3) access specified object element using string_view with bounds checking"
|
||||
|
||||
The example below shows how object elements can be read and written using `at()`. It also demonstrates the different
|
||||
exceptions that can be thrown.
|
||||
|
||||
```cpp
|
||||
--8<-- "examples/at__keytype.c++17.cpp"
|
||||
```
|
||||
|
||||
Output:
|
||||
|
||||
```json
|
||||
--8<-- "examples/at__keytype.c++17.output"
|
||||
```
|
||||
|
||||
??? example "Example: (3) access specified object element using string_view with bounds checking"
|
||||
|
||||
The example below shows how object elements can be read using `at()`. It also demonstrates the different exceptions
|
||||
that can be thrown.
|
||||
|
||||
```cpp
|
||||
--8<-- "examples/at__keytype_const.c++17.cpp"
|
||||
```
|
||||
|
||||
Output:
|
||||
|
||||
```json
|
||||
--8<-- "examples/at__keytype_const.c++17.output"
|
||||
```
|
||||
|
||||
??? example "Example: (4) access specified element via JSON Pointer"
|
||||
|
||||
The example below shows how object elements can be read and written using `at()`. It also demonstrates the different
|
||||
exceptions that can be thrown.
|
||||
|
||||
```cpp
|
||||
--8<-- "examples/at__json_pointer.cpp"
|
||||
```
|
||||
|
||||
Output:
|
||||
|
||||
```json
|
||||
--8<-- "examples/at__json_pointer.output"
|
||||
```
|
||||
|
||||
??? example "Example: (4) access specified element via JSON Pointer"
|
||||
|
||||
The example below shows how object elements can be read using `at()`. It also demonstrates the different exceptions
|
||||
that can be thrown.
|
||||
|
||||
```cpp
|
||||
--8<-- "examples/at__json_pointer_const.cpp"
|
||||
```
|
||||
|
||||
Output:
|
||||
|
||||
```json
|
||||
--8<-- "examples/at__json_pointer_const.output"
|
||||
```
|
||||
|
||||
## See also
|
||||
|
||||
- documentation on [checked access](../../features/element_access/checked_access.md)
|
||||
- [`operator[]`](operator%5B%5D.md) for unchecked access by reference
|
||||
- [`value`](value.md) for access with default value
|
||||
|
||||
## Version history
|
||||
|
||||
1. Added in version 1.0.0.
|
||||
2. Added in version 1.0.0.
|
||||
3. Added in version 3.11.0.
|
||||
4. Added in version 2.0.0.
|
||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1,668 @@
|
||||
# nlohmann::basic_json::at
|
||||
|
||||
```
|
||||
// (1)
|
||||
reference at(size_type idx);
|
||||
const_reference at(size_type idx) const;
|
||||
|
||||
// (2)
|
||||
reference at(const typename object_t::key_type& key);
|
||||
const_reference at(const typename object_t::key_type& key) const;
|
||||
|
||||
// (3)
|
||||
template<typename KeyType>
|
||||
reference at(KeyType&& key);
|
||||
template<typename KeyType>
|
||||
const_reference at(KeyType&& key) const;
|
||||
|
||||
// (4)
|
||||
reference at(const json_pointer& ptr);
|
||||
const_reference at(const json_pointer& ptr) const;
|
||||
```
|
||||
|
||||
1. Returns a reference to the array element at specified location `idx`, with bounds checking.
|
||||
1. Returns a reference to the object element with specified key `key`, with bounds checking.
|
||||
1. See 2. This overload is only available if `KeyType` is comparable with `typename object_t::key_type` and `typename object_comparator_t::is_transparent` denotes a type.
|
||||
1. Returns a reference to the element at specified JSON pointer `ptr`, with bounds checking.
|
||||
|
||||
## Template parameters
|
||||
|
||||
`KeyType` : A type for an object key other than [`json_pointer`](https://json.nlohmann.me/api/json_pointer/index.md) that is comparable with [`string_t`](https://json.nlohmann.me/api/basic_json/string_t/index.md) using [`object_comparator_t`](https://json.nlohmann.me/api/basic_json/object_comparator_t/index.md). This can also be a string view (C++17).
|
||||
|
||||
## Parameters
|
||||
|
||||
`idx` (in) : index of the element to access
|
||||
|
||||
`key` (in) : object key of the elements to access
|
||||
|
||||
`ptr` (in) : JSON pointer to the desired element
|
||||
|
||||
## Return value
|
||||
|
||||
1. reference to the element at index `idx`
|
||||
1. reference to the element at key `key`
|
||||
1. reference to the element at key `key`
|
||||
1. reference to the element pointed to by `ptr`
|
||||
|
||||
## Exception safety
|
||||
|
||||
Strong exception safety: if an exception occurs, the original value stays intact.
|
||||
|
||||
## Exceptions
|
||||
|
||||
1. The function can throw the following exceptions:
|
||||
- Throws [`type_error.304`](https://json.nlohmann.me/home/exceptions/#jsonexceptiontype_error304) if the JSON value is not an array; in this case, calling `at` with an index makes no sense. See the example below.
|
||||
- Throws [`out_of_range.401`](https://json.nlohmann.me/home/exceptions/#jsonexceptionout_of_range401) if the index `idx` is out of range of the array; that is, `idx >= size()`. See the example below.
|
||||
1. The function can throw the following exceptions:
|
||||
- Throws [`type_error.304`](https://json.nlohmann.me/home/exceptions/#jsonexceptiontype_error304) if the JSON value is not an object; in this case, calling `at` with a key makes no sense. See the example below.
|
||||
- Throws [`out_of_range.403`](https://json.nlohmann.me/home/exceptions/#jsonexceptionout_of_range403) if the key `key` is not stored in the object; that is, `find(key) == end()`. See the example below.
|
||||
1. See 2.
|
||||
1. The function can throw the following exceptions:
|
||||
- Throws [`parse_error.106`](https://json.nlohmann.me/home/exceptions/#jsonexceptionparse_error106) if an array index in the passed JSON pointer `ptr` begins with '0'. See the example below.
|
||||
- Throws [`parse_error.109`](https://json.nlohmann.me/home/exceptions/#jsonexceptionparse_error109) if an array index in the passed JSON pointer `ptr` is not a number. See the example below.
|
||||
- Throws [`out_of_range.401`](https://json.nlohmann.me/home/exceptions/#jsonexceptionout_of_range401) if an array index in the passed JSON pointer `ptr` is out of range. See the example below.
|
||||
- Throws [`out_of_range.402`](https://json.nlohmann.me/home/exceptions/#jsonexceptionout_of_range402) if the array index '-' is used in the passed JSON pointer `ptr`. As `at` provides checked access (and no elements are implicitly inserted), the index '-' is always invalid. See the example below.
|
||||
- Throws [`out_of_range.403`](https://json.nlohmann.me/home/exceptions/#jsonexceptionout_of_range403) if the JSON pointer describes a key of an object which cannot be found. See the example below.
|
||||
- Throws [`out_of_range.404`](https://json.nlohmann.me/home/exceptions/#jsonexceptionout_of_range404) if the JSON pointer `ptr` can not be resolved. See the example below.
|
||||
- Throws [`out_of_range.410`](https://json.nlohmann.me/home/exceptions/#jsonexceptionout_of_range410) if an array index in the passed JSON pointer `ptr` exceeds the range of `size_type` (e.g., on 32-bit platforms).
|
||||
|
||||
## Complexity
|
||||
|
||||
1. Constant.
|
||||
1. Logarithmic in the size of the container.
|
||||
1. Logarithmic in the size of the container.
|
||||
1. Logarithmic in the size of the container.
|
||||
|
||||
## Examples
|
||||
|
||||
Example: (1) access specified array element with bounds checking
|
||||
|
||||
The example below shows how array elements can be read and written using `at()`. It also demonstrates the different exceptions that can be thrown.
|
||||
|
||||
```
|
||||
#include <iostream>
|
||||
#include <nlohmann/json.hpp>
|
||||
|
||||
using json = nlohmann::json;
|
||||
|
||||
int main()
|
||||
{
|
||||
// create JSON array
|
||||
json array = {"first", "2nd", "third", "fourth"};
|
||||
|
||||
// output element at index 2 (third element)
|
||||
std::cout << array.at(2) << '\n';
|
||||
|
||||
// change element at index 1 (second element) to "second"
|
||||
array.at(1) = "second";
|
||||
|
||||
// output changed array
|
||||
std::cout << array << '\n';
|
||||
|
||||
// exception type_error.304
|
||||
try
|
||||
{
|
||||
// use at() on a non-array type
|
||||
json str = "I am a string";
|
||||
str.at(0) = "Another string";
|
||||
}
|
||||
catch (const json::type_error& e)
|
||||
{
|
||||
std::cout << e.what() << '\n';
|
||||
}
|
||||
|
||||
// exception out_of_range.401
|
||||
try
|
||||
{
|
||||
// try to write beyond the array limit
|
||||
array.at(5) = "sixth";
|
||||
}
|
||||
catch (const json::out_of_range& e)
|
||||
{
|
||||
std::cout << e.what() << '\n';
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Output:
|
||||
|
||||
```
|
||||
"third"
|
||||
["first","second","third","fourth"]
|
||||
[json.exception.type_error.304] cannot use at() with string
|
||||
[json.exception.out_of_range.401] array index 5 is out of range
|
||||
```
|
||||
|
||||
Example: (1) access specified array element with bounds checking
|
||||
|
||||
The example below shows how array elements can be read using `at()`. It also demonstrates the different exceptions that can be thrown.
|
||||
|
||||
```
|
||||
#include <iostream>
|
||||
#include <nlohmann/json.hpp>
|
||||
|
||||
using json = nlohmann::json;
|
||||
|
||||
int main()
|
||||
{
|
||||
// create JSON array
|
||||
const json array = {"first", "2nd", "third", "fourth"};
|
||||
|
||||
// output element at index 2 (third element)
|
||||
std::cout << array.at(2) << '\n';
|
||||
|
||||
// exception type_error.304
|
||||
try
|
||||
{
|
||||
// use at() on a non-array type
|
||||
const json str = "I am a string";
|
||||
std::cout << str.at(0) << '\n';
|
||||
}
|
||||
catch (const json::type_error& e)
|
||||
{
|
||||
std::cout << e.what() << '\n';
|
||||
}
|
||||
|
||||
// exception out_of_range.401
|
||||
try
|
||||
{
|
||||
// try to read beyond the array limit
|
||||
std::cout << array.at(5) << '\n';
|
||||
}
|
||||
catch (const json::out_of_range& e)
|
||||
{
|
||||
std::cout << e.what() << '\n';
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Output:
|
||||
|
||||
```
|
||||
"third"
|
||||
[json.exception.type_error.304] cannot use at() with string
|
||||
[json.exception.out_of_range.401] array index 5 is out of range
|
||||
```
|
||||
|
||||
Example: (2) access specified object element with bounds checking
|
||||
|
||||
The example below shows how object elements can be read and written using `at()`. It also demonstrates the different exceptions that can be thrown.
|
||||
|
||||
```
|
||||
#include <iostream>
|
||||
#include <nlohmann/json.hpp>
|
||||
|
||||
using json = nlohmann::json;
|
||||
|
||||
int main()
|
||||
{
|
||||
// create JSON object
|
||||
json object =
|
||||
{
|
||||
{"the good", "il buono"},
|
||||
{"the bad", "il cattivo"},
|
||||
{"the ugly", "il brutto"}
|
||||
};
|
||||
|
||||
// output element with key "the ugly"
|
||||
std::cout << object.at("the ugly") << '\n';
|
||||
|
||||
// change element with key "the bad"
|
||||
object.at("the bad") = "il cattivo";
|
||||
|
||||
// output changed array
|
||||
std::cout << object << '\n';
|
||||
|
||||
// exception type_error.304
|
||||
try
|
||||
{
|
||||
// use at() on a non-object type
|
||||
json str = "I am a string";
|
||||
str.at("the good") = "Another string";
|
||||
}
|
||||
catch (const json::type_error& e)
|
||||
{
|
||||
std::cout << e.what() << '\n';
|
||||
}
|
||||
|
||||
// exception out_of_range.401
|
||||
try
|
||||
{
|
||||
// try to write at a nonexisting key
|
||||
object.at("the fast") = "il rapido";
|
||||
}
|
||||
catch (const json::out_of_range& e)
|
||||
{
|
||||
std::cout << e.what() << '\n';
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Output:
|
||||
|
||||
```
|
||||
"il brutto"
|
||||
{"the bad":"il cattivo","the good":"il buono","the ugly":"il brutto"}
|
||||
[json.exception.type_error.304] cannot use at() with string
|
||||
[json.exception.out_of_range.403] key 'the fast' not found
|
||||
```
|
||||
|
||||
Example: (2) access specified object element with bounds checking
|
||||
|
||||
The example below shows how object elements can be read using `at()`. It also demonstrates the different exceptions that can be thrown.
|
||||
|
||||
```
|
||||
#include <iostream>
|
||||
#include <nlohmann/json.hpp>
|
||||
|
||||
using json = nlohmann::json;
|
||||
|
||||
int main()
|
||||
{
|
||||
// create JSON object
|
||||
const json object =
|
||||
{
|
||||
{"the good", "il buono"},
|
||||
{"the bad", "il cattivo"},
|
||||
{"the ugly", "il brutto"}
|
||||
};
|
||||
|
||||
// output element with key "the ugly"
|
||||
std::cout << object.at("the ugly") << '\n';
|
||||
|
||||
// exception type_error.304
|
||||
try
|
||||
{
|
||||
// use at() on a non-object type
|
||||
const json str = "I am a string";
|
||||
std::cout << str.at("the good") << '\n';
|
||||
}
|
||||
catch (const json::type_error& e)
|
||||
{
|
||||
std::cout << e.what() << '\n';
|
||||
}
|
||||
|
||||
// exception out_of_range.401
|
||||
try
|
||||
{
|
||||
// try to read from a nonexisting key
|
||||
std::cout << object.at("the fast") << '\n';
|
||||
}
|
||||
catch (const json::out_of_range)
|
||||
{
|
||||
std::cout << "out of range" << '\n';
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Output:
|
||||
|
||||
```
|
||||
"il brutto"
|
||||
[json.exception.type_error.304] cannot use at() with string
|
||||
out of range
|
||||
```
|
||||
|
||||
Example: (3) access specified object element using string_view with bounds checking
|
||||
|
||||
The example below shows how object elements can be read and written using `at()`. It also demonstrates the different exceptions that can be thrown.
|
||||
|
||||
```
|
||||
#include <iostream>
|
||||
#include <string_view>
|
||||
#include <nlohmann/json.hpp>
|
||||
|
||||
using namespace std::string_view_literals;
|
||||
using json = nlohmann::json;
|
||||
|
||||
int main()
|
||||
{
|
||||
// create JSON object
|
||||
json object =
|
||||
{
|
||||
{"the good", "il buono"},
|
||||
{"the bad", "il cattivo"},
|
||||
{"the ugly", "il brutto"}
|
||||
};
|
||||
|
||||
// output element with key "the ugly" using string_view
|
||||
std::cout << object.at("the ugly"sv) << '\n';
|
||||
|
||||
// change element with key "the bad" using string_view
|
||||
object.at("the bad"sv) = "il cattivo";
|
||||
|
||||
// output changed array
|
||||
std::cout << object << '\n';
|
||||
|
||||
// exception type_error.304
|
||||
try
|
||||
{
|
||||
// use at() with string_view on a non-object type
|
||||
json str = "I am a string";
|
||||
str.at("the good"sv) = "Another string";
|
||||
}
|
||||
catch (const json::type_error& e)
|
||||
{
|
||||
std::cout << e.what() << '\n';
|
||||
}
|
||||
|
||||
// exception out_of_range.401
|
||||
try
|
||||
{
|
||||
// try to write at a nonexisting key using string_view
|
||||
object.at("the fast"sv) = "il rapido";
|
||||
}
|
||||
catch (const json::out_of_range& e)
|
||||
{
|
||||
std::cout << e.what() << '\n';
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Output:
|
||||
|
||||
```
|
||||
"il brutto"
|
||||
{"the bad":"il cattivo","the good":"il buono","the ugly":"il brutto"}
|
||||
[json.exception.type_error.304] cannot use at() with string
|
||||
[json.exception.out_of_range.403] key 'the fast' not found
|
||||
```
|
||||
|
||||
Example: (3) access specified object element using string_view with bounds checking
|
||||
|
||||
The example below shows how object elements can be read using `at()`. It also demonstrates the different exceptions that can be thrown.
|
||||
|
||||
```
|
||||
#include <iostream>
|
||||
#include <string_view>
|
||||
#include <nlohmann/json.hpp>
|
||||
|
||||
using namespace std::string_view_literals;
|
||||
using json = nlohmann::json;
|
||||
|
||||
int main()
|
||||
{
|
||||
// create JSON object
|
||||
const json object =
|
||||
{
|
||||
{"the good", "il buono"},
|
||||
{"the bad", "il cattivo"},
|
||||
{"the ugly", "il brutto"}
|
||||
};
|
||||
|
||||
// output element with key "the ugly" using string_view
|
||||
std::cout << object.at("the ugly"sv) << '\n';
|
||||
|
||||
// exception type_error.304
|
||||
try
|
||||
{
|
||||
// use at() with string_view on a non-object type
|
||||
const json str = "I am a string";
|
||||
std::cout << str.at("the good"sv) << '\n';
|
||||
}
|
||||
catch (const json::type_error& e)
|
||||
{
|
||||
std::cout << e.what() << '\n';
|
||||
}
|
||||
|
||||
// exception out_of_range.401
|
||||
try
|
||||
{
|
||||
// try to read from a nonexisting key using string_view
|
||||
std::cout << object.at("the fast"sv) << '\n';
|
||||
}
|
||||
catch (const json::out_of_range& e)
|
||||
{
|
||||
std::cout << "out of range" << '\n';
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Output:
|
||||
|
||||
```
|
||||
"il brutto"
|
||||
[json.exception.type_error.304] cannot use at() with string
|
||||
out of range
|
||||
```
|
||||
|
||||
Example: (4) access specified element via JSON Pointer
|
||||
|
||||
The example below shows how object elements can be read and written using `at()`. It also demonstrates the different exceptions that can be thrown.
|
||||
|
||||
```
|
||||
#include <iostream>
|
||||
#include <nlohmann/json.hpp>
|
||||
|
||||
using json = nlohmann::json;
|
||||
using namespace nlohmann::literals;
|
||||
|
||||
int main()
|
||||
{
|
||||
// create a JSON value
|
||||
json j =
|
||||
{
|
||||
{"number", 1}, {"string", "foo"}, {"array", {1, 2}}
|
||||
};
|
||||
|
||||
// read-only access
|
||||
|
||||
// output element with JSON pointer "/number"
|
||||
std::cout << j.at("/number"_json_pointer) << '\n';
|
||||
// output element with JSON pointer "/string"
|
||||
std::cout << j.at("/string"_json_pointer) << '\n';
|
||||
// output element with JSON pointer "/array"
|
||||
std::cout << j.at("/array"_json_pointer) << '\n';
|
||||
// output element with JSON pointer "/array/1"
|
||||
std::cout << j.at("/array/1"_json_pointer) << '\n';
|
||||
|
||||
// writing access
|
||||
|
||||
// change the string
|
||||
j.at("/string"_json_pointer) = "bar";
|
||||
// output the changed string
|
||||
std::cout << j["string"] << '\n';
|
||||
|
||||
// change an array element
|
||||
j.at("/array/1"_json_pointer) = 21;
|
||||
// output the changed array
|
||||
std::cout << j["array"] << '\n';
|
||||
|
||||
// out_of_range.106
|
||||
try
|
||||
{
|
||||
// try to use an array index with leading '0'
|
||||
json::reference ref = j.at("/array/01"_json_pointer);
|
||||
}
|
||||
catch (const json::parse_error& e)
|
||||
{
|
||||
std::cout << e.what() << '\n';
|
||||
}
|
||||
|
||||
// out_of_range.109
|
||||
try
|
||||
{
|
||||
// try to use an array index that is not a number
|
||||
json::reference ref = j.at("/array/one"_json_pointer);
|
||||
}
|
||||
catch (const json::parse_error& e)
|
||||
{
|
||||
std::cout << e.what() << '\n';
|
||||
}
|
||||
|
||||
// out_of_range.401
|
||||
try
|
||||
{
|
||||
// try to use an invalid array index
|
||||
json::reference ref = j.at("/array/4"_json_pointer);
|
||||
}
|
||||
catch (const json::out_of_range& e)
|
||||
{
|
||||
std::cout << e.what() << '\n';
|
||||
}
|
||||
|
||||
// out_of_range.402
|
||||
try
|
||||
{
|
||||
// try to use the array index '-'
|
||||
json::reference ref = j.at("/array/-"_json_pointer);
|
||||
}
|
||||
catch (const json::out_of_range& e)
|
||||
{
|
||||
std::cout << e.what() << '\n';
|
||||
}
|
||||
|
||||
// out_of_range.403
|
||||
try
|
||||
{
|
||||
// try to use a JSON pointer to a nonexistent object key
|
||||
json::const_reference ref = j.at("/foo"_json_pointer);
|
||||
}
|
||||
catch (const json::out_of_range& e)
|
||||
{
|
||||
std::cout << e.what() << '\n';
|
||||
}
|
||||
|
||||
// out_of_range.404
|
||||
try
|
||||
{
|
||||
// try to use a JSON pointer that cannot be resolved
|
||||
json::reference ref = j.at("/number/foo"_json_pointer);
|
||||
}
|
||||
catch (const json::out_of_range& e)
|
||||
{
|
||||
std::cout << e.what() << '\n';
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Output:
|
||||
|
||||
```
|
||||
1
|
||||
"foo"
|
||||
[1,2]
|
||||
2
|
||||
"bar"
|
||||
[1,21]
|
||||
[json.exception.parse_error.106] parse error: array index '01' must not begin with '0'
|
||||
[json.exception.parse_error.109] parse error: array index 'one' is not a number
|
||||
[json.exception.out_of_range.401] array index 4 is out of range
|
||||
[json.exception.out_of_range.402] array index '-' (2) is out of range
|
||||
[json.exception.out_of_range.403] key 'foo' not found
|
||||
[json.exception.out_of_range.404] unresolved reference token 'foo'
|
||||
```
|
||||
|
||||
Example: (4) access specified element via JSON Pointer
|
||||
|
||||
The example below shows how object elements can be read using `at()`. It also demonstrates the different exceptions that can be thrown.
|
||||
|
||||
```
|
||||
#include <iostream>
|
||||
#include <nlohmann/json.hpp>
|
||||
|
||||
using json = nlohmann::json;
|
||||
using namespace nlohmann::literals;
|
||||
|
||||
int main()
|
||||
{
|
||||
// create a JSON value
|
||||
const json j =
|
||||
{
|
||||
{"number", 1}, {"string", "foo"}, {"array", {1, 2}}
|
||||
};
|
||||
|
||||
// read-only access
|
||||
|
||||
// output element with JSON pointer "/number"
|
||||
std::cout << j.at("/number"_json_pointer) << '\n';
|
||||
// output element with JSON pointer "/string"
|
||||
std::cout << j.at("/string"_json_pointer) << '\n';
|
||||
// output element with JSON pointer "/array"
|
||||
std::cout << j.at("/array"_json_pointer) << '\n';
|
||||
// output element with JSON pointer "/array/1"
|
||||
std::cout << j.at("/array/1"_json_pointer) << '\n';
|
||||
|
||||
// out_of_range.109
|
||||
try
|
||||
{
|
||||
// try to use an array index that is not a number
|
||||
json::const_reference ref = j.at("/array/one"_json_pointer);
|
||||
}
|
||||
catch (const json::parse_error& e)
|
||||
{
|
||||
std::cout << e.what() << '\n';
|
||||
}
|
||||
|
||||
// out_of_range.401
|
||||
try
|
||||
{
|
||||
// try to use an invalid array index
|
||||
json::const_reference ref = j.at("/array/4"_json_pointer);
|
||||
}
|
||||
catch (const json::out_of_range& e)
|
||||
{
|
||||
std::cout << e.what() << '\n';
|
||||
}
|
||||
|
||||
// out_of_range.402
|
||||
try
|
||||
{
|
||||
// try to use the array index '-'
|
||||
json::const_reference ref = j.at("/array/-"_json_pointer);
|
||||
}
|
||||
catch (const json::out_of_range& e)
|
||||
{
|
||||
std::cout << e.what() << '\n';
|
||||
}
|
||||
|
||||
// out_of_range.403
|
||||
try
|
||||
{
|
||||
// try to use a JSON pointer to a nonexistent object key
|
||||
json::const_reference ref = j.at("/foo"_json_pointer);
|
||||
}
|
||||
catch (const json::out_of_range& e)
|
||||
{
|
||||
std::cout << e.what() << '\n';
|
||||
}
|
||||
|
||||
// out_of_range.404
|
||||
try
|
||||
{
|
||||
// try to use a JSON pointer that cannot be resolved
|
||||
json::const_reference ref = j.at("/number/foo"_json_pointer);
|
||||
}
|
||||
catch (const json::out_of_range& e)
|
||||
{
|
||||
std::cout << e.what() << '\n';
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Output:
|
||||
|
||||
```
|
||||
1
|
||||
"foo"
|
||||
[1,2]
|
||||
2
|
||||
[json.exception.parse_error.109] parse error: array index 'one' is not a number
|
||||
[json.exception.out_of_range.401] array index 4 is out of range
|
||||
[json.exception.out_of_range.402] array index '-' (2) is out of range
|
||||
[json.exception.out_of_range.403] key 'foo' not found
|
||||
[json.exception.out_of_range.404] unresolved reference token 'foo'
|
||||
```
|
||||
|
||||
## See also
|
||||
|
||||
- documentation on [checked access](https://json.nlohmann.me/features/element_access/checked_access/index.md)
|
||||
- [`operator[]`](https://json.nlohmann.me/api/basic_json/operator%5B%5D/index.md) for unchecked access by reference
|
||||
- [`value`](https://json.nlohmann.me/api/basic_json/value/index.md) for access with default value
|
||||
|
||||
## Version history
|
||||
|
||||
1. Added in version 1.0.0.
|
||||
1. Added in version 1.0.0.
|
||||
1. Added in version 3.11.0.
|
||||
1. Added in version 2.0.0.
|
||||
@@ -0,0 +1,65 @@
|
||||
# <small>nlohmann::basic_json::</small>back
|
||||
|
||||
```cpp
|
||||
reference back();
|
||||
|
||||
const_reference back() const;
|
||||
```
|
||||
|
||||
Returns a reference to the last element in the container. For a JSON container `c`, the expression `c.back()` is
|
||||
equivalent to
|
||||
|
||||
```cpp
|
||||
auto tmp = c.end();
|
||||
--tmp;
|
||||
return *tmp;
|
||||
```
|
||||
|
||||
## Return value
|
||||
|
||||
In the case of a structured type (array or object), a reference to the last element is returned. In the case of number,
|
||||
string, boolean, or binary values, a reference to the value is returned.
|
||||
|
||||
## Exception safety
|
||||
|
||||
Strong guarantee: if an exception is thrown, there are no changes in the JSON value.
|
||||
|
||||
## Exceptions
|
||||
|
||||
If the JSON value is `#!json null`, exception
|
||||
[`invalid_iterator.214`](../../home/exceptions.md#jsonexceptioninvalid_iterator214) is thrown.
|
||||
|
||||
## Complexity
|
||||
|
||||
Constant.
|
||||
|
||||
## Notes
|
||||
|
||||
!!! info "Precondition"
|
||||
|
||||
The array or object must not be empty. Calling `back` on an empty array or object yields undefined behavior.
|
||||
|
||||
## Examples
|
||||
|
||||
??? example
|
||||
|
||||
The following code shows an example for `back()`.
|
||||
|
||||
```cpp
|
||||
--8<-- "examples/back.cpp"
|
||||
```
|
||||
|
||||
Output:
|
||||
|
||||
```json
|
||||
--8<-- "examples/back.output"
|
||||
```
|
||||
|
||||
## See also
|
||||
|
||||
- [front](front.md) to access the first element
|
||||
|
||||
## Version history
|
||||
|
||||
- Added in version 1.0.0.
|
||||
- Adjusted code to return reference to binary values in version 3.8.0.
|
||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1,105 @@
|
||||
# nlohmann::basic_json::back
|
||||
|
||||
```
|
||||
reference back();
|
||||
|
||||
const_reference back() const;
|
||||
```
|
||||
|
||||
Returns a reference to the last element in the container. For a JSON container `c`, the expression `c.back()` is equivalent to
|
||||
|
||||
```
|
||||
auto tmp = c.end();
|
||||
--tmp;
|
||||
return *tmp;
|
||||
```
|
||||
|
||||
## Return value
|
||||
|
||||
In the case of a structured type (array or object), a reference to the last element is returned. In the case of number, string, boolean, or binary values, a reference to the value is returned.
|
||||
|
||||
## Exception safety
|
||||
|
||||
Strong guarantee: if an exception is thrown, there are no changes in the JSON value.
|
||||
|
||||
## Exceptions
|
||||
|
||||
If the JSON value is `null`, exception [`invalid_iterator.214`](https://json.nlohmann.me/home/exceptions/#jsonexceptioninvalid_iterator214) is thrown.
|
||||
|
||||
## Complexity
|
||||
|
||||
Constant.
|
||||
|
||||
## Notes
|
||||
|
||||
Precondition
|
||||
|
||||
The array or object must not be empty. Calling `back` on an empty array or object yields undefined behavior.
|
||||
|
||||
## Examples
|
||||
|
||||
Example
|
||||
|
||||
The following code shows an example for `back()`.
|
||||
|
||||
```
|
||||
#include <iostream>
|
||||
#include <nlohmann/json.hpp>
|
||||
|
||||
using json = nlohmann::json;
|
||||
|
||||
int main()
|
||||
{
|
||||
// create JSON values
|
||||
json j_boolean = true;
|
||||
json j_number_integer = 17;
|
||||
json j_number_float = 23.42;
|
||||
json j_object = {{"one", 1}, {"two", 2}};
|
||||
json j_object_empty(json::value_t::object);
|
||||
json j_array = {1, 2, 4, 8, 16};
|
||||
json j_array_empty(json::value_t::array);
|
||||
json j_string = "Hello, world";
|
||||
|
||||
// call back()
|
||||
std::cout << j_boolean.back() << '\n';
|
||||
std::cout << j_number_integer.back() << '\n';
|
||||
std::cout << j_number_float.back() << '\n';
|
||||
std::cout << j_object.back() << '\n';
|
||||
//std::cout << j_object_empty.back() << '\n'; // undefined behavior
|
||||
std::cout << j_array.back() << '\n';
|
||||
//std::cout << j_array_empty.back() << '\n'; // undefined behavior
|
||||
std::cout << j_string.back() << '\n';
|
||||
|
||||
// back() called on a null value
|
||||
try
|
||||
{
|
||||
json j_null;
|
||||
j_null.back();
|
||||
}
|
||||
catch (const json::invalid_iterator& e)
|
||||
{
|
||||
std::cout << e.what() << '\n';
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Output:
|
||||
|
||||
```
|
||||
true
|
||||
17
|
||||
23.42
|
||||
2
|
||||
16
|
||||
"Hello, world"
|
||||
[json.exception.invalid_iterator.214] cannot get value
|
||||
```
|
||||
|
||||
## See also
|
||||
|
||||
- [front](https://json.nlohmann.me/api/basic_json/front/index.md) to access the first element
|
||||
|
||||
## Version history
|
||||
|
||||
- Added in version 1.0.0.
|
||||
- Adjusted code to return reference to binary values in version 3.8.0.
|
||||
@@ -0,0 +1,428 @@
|
||||
# <small>nlohmann::basic_json::</small>basic_json
|
||||
|
||||
```cpp
|
||||
// (1)
|
||||
basic_json(const value_t v);
|
||||
|
||||
// (2)
|
||||
basic_json(std::nullptr_t = nullptr) noexcept;
|
||||
|
||||
// (3)
|
||||
template<typename CompatibleType>
|
||||
basic_json(CompatibleType&& val) noexcept(noexcept(
|
||||
JSONSerializer<U>::to_json(std::declval<basic_json_t&>(),
|
||||
std::forward<CompatibleType>(val))));
|
||||
|
||||
// (4)
|
||||
template<typename BasicJsonType>
|
||||
basic_json(const BasicJsonType& val);
|
||||
|
||||
// (5)
|
||||
basic_json(initializer_list_t init,
|
||||
bool type_deduction = true,
|
||||
value_t manual_type = value_t::array);
|
||||
|
||||
// (6)
|
||||
basic_json(size_type cnt, const basic_json& val);
|
||||
|
||||
// (7)
|
||||
basic_json(iterator first, iterator last);
|
||||
basic_json(const_iterator first, const_iterator last);
|
||||
|
||||
// (8)
|
||||
basic_json(const basic_json& other);
|
||||
|
||||
// (9)
|
||||
basic_json(basic_json&& other) noexcept;
|
||||
```
|
||||
|
||||
1. Create an empty JSON value with a given type. The value will be default initialized with an empty value which depends
|
||||
on the type:
|
||||
|
||||
| Value type | initial value |
|
||||
|------------|----------------|
|
||||
| null | `#!json null` |
|
||||
| boolean | `#!json false` |
|
||||
| string | `#!json ""` |
|
||||
| number | `#!json 0` |
|
||||
| object | `#!json {}` |
|
||||
| array | `#!json []` |
|
||||
| binary | empty array |
|
||||
|
||||
The postcondition of this constructor can be restored by calling [`clear()`](clear.md).
|
||||
|
||||
2. Create a `#!json null` JSON value. It either takes a null pointer as parameter (explicitly creating `#!json null`)
|
||||
or no parameter (implicitly creating `#!json null`). The passed null pointer itself is not read -- it is only used to
|
||||
choose the right constructor.
|
||||
|
||||
3. This is a "catch all" constructor for all compatible JSON types; that is, types for which a `to_json()` method
|
||||
exists. The constructor forwards the parameter `val` to that method (to `json_serializer<U>::to_json` method with
|
||||
`U = uncvref_t<CompatibleType>`, to be exact).
|
||||
|
||||
Template type `CompatibleType` includes, but is not limited to, the following types:
|
||||
|
||||
- **arrays**: [`array_t`](array_t.md) and all kinds of compatible containers such as `std::vector`, `std::deque`,
|
||||
`std::list`, `std::forward_list`, `std::array`, `std::valarray`, `std::set`, `std::unordered_set`, `std::multiset`,
|
||||
and `std::unordered_multiset` with a `value_type` from which a `basic_json` value can be constructed.
|
||||
- **objects**: [`object_t`](object_t.md) and all kinds of compatible associative containers such as `std::map`,
|
||||
`std::unordered_map`, `std::multimap`, and `std::unordered_multimap` with a `key_type` compatible to `string_t`
|
||||
and a `value_type` from which a `basic_json` value can be constructed.
|
||||
- **strings**: `string_t`, string literals, and all compatible string containers can be used.
|
||||
- **numbers**: [`number_integer_t`](number_integer_t.md), [`number_unsigned_t`](number_unsigned_t.md),
|
||||
[`number_float_t`](number_float_t.md), and all convertible number types such as `int`, `size_t`, `int64_t`, `float`
|
||||
or `double` can be used.
|
||||
- **boolean**: `boolean_t` / `bool` can be used.
|
||||
- **binary**: `binary_t` / `std::vector<uint8_t>` may be used; unfortunately because string literals cannot be
|
||||
distinguished from binary character arrays by the C++ type system, all types compatible with `const char*` will be
|
||||
directed to the string constructor instead. This is both for backwards compatibility and due to the fact that a
|
||||
binary type is not a standard JSON type.
|
||||
|
||||
See the examples below.
|
||||
|
||||
4. This is a constructor for existing `basic_json` types. It does not hijack copy/move constructors, since the parameter
|
||||
has different template arguments than the current ones.
|
||||
|
||||
The constructor tries to convert the internal `m_value` of the parameter. Each member value (object, array, string,
|
||||
etc.) is serialized via the corresponding `to_json()` overload. For objects and strings, the conversion requires
|
||||
that the *target* `basic_json` type's `object_t::key_type` (or `string_t`) be directly constructible from the
|
||||
*source* type's corresponding member type via `is_constructible`. If this requirement is not met, the conversion
|
||||
does not fail to compile; instead, it silently falls back to the array-conversion path, which represents objects
|
||||
as arrays of `[key, value]` pairs and strings as arrays of character codes. This is a known limitation tracked in
|
||||
[issue #3425](https://github.com/nlohmann/json/issues/3425).
|
||||
|
||||
5. Creates a JSON value of type array or object from the passed initializer list `init`. In case `type_deduction` is
|
||||
`#!cpp true` (default), the type of the JSON value to be created is deducted from the initializer list `init`
|
||||
according to the following rules:
|
||||
|
||||
1. If the list is empty, an empty JSON object value `{}` is created.
|
||||
2. If the list consists of pairs whose first element is a string, a JSON object value is created where the first
|
||||
elements of the pairs are treated as keys and the second elements are as values.
|
||||
3. In all other cases, an array is created.
|
||||
|
||||
The rules aim to create the best fit between a C++ initializer list and JSON values. The rationale is as follows:
|
||||
|
||||
1. The empty initializer list is written as `#!cpp {}` which is exactly an empty JSON object.
|
||||
2. C++ has no way of describing mapped types other than to list a list of pairs. As JSON requires that keys must be
|
||||
of type string, rule 2 is the weakest constraint one can pose on initializer lists to interpret them as an
|
||||
object.
|
||||
3. In all other cases, the initializer list could not be interpreted as a JSON object type, so interpreting it as a
|
||||
JSON array type is safe.
|
||||
|
||||
With the rules described above, the following JSON values cannot be expressed by an initializer list:
|
||||
|
||||
- the empty array (`#!json []`): use `array(initializer_list_t)` with an empty initializer list in this case
|
||||
- arrays whose elements satisfy rule 2: use `array(initializer_list_t)` with the same initializer list in this case
|
||||
|
||||
Function [`array()`](array.md) and [`object()`](object.md) force array and object creation from initializer lists,
|
||||
respectively.
|
||||
|
||||
!!! warning "Brace initialization yields arrays"
|
||||
|
||||
Because this constructor takes an `initializer_list_t`, brace-initializing a `json`/`ordered_json` from
|
||||
another `json` value wraps it in a single-element array rather than copying it:
|
||||
|
||||
```cpp
|
||||
json j1 = "hello";
|
||||
json j2{j1}; // [!] j2 is ["hello"], NOT a copy of j1
|
||||
json j3(j1); // j3 is "hello" -- parentheses copy as expected
|
||||
```
|
||||
|
||||
See the FAQ entry on [brace initialization](../../home/faq.md#brace-initialization-yields-arrays) for the
|
||||
full explanation, an opt-in macro to change this behavior, and how to explicitly create a single-element
|
||||
array (`json::array({value})`) if that is what you want.
|
||||
|
||||
6. Constructs a JSON array value by creating `cnt` copies of a passed value. In case `cnt` is `0`, an empty array is
|
||||
created.
|
||||
|
||||
7. Constructs the JSON value with the contents of the range `[first, last)`. The semantics depend on the different
|
||||
types a JSON value can have:
|
||||
|
||||
- In case of a `#!json null` type, [invalid_iterator.206](../../home/exceptions.md#jsonexceptioninvalid_iterator206)
|
||||
is thrown.
|
||||
- In case of other primitive types (number, boolean, or string), `first` must be `begin()` and `last` must be
|
||||
`end()`. In this case, the value is copied. Otherwise,
|
||||
[`invalid_iterator.204`](../../home/exceptions.md#jsonexceptioninvalid_iterator204) is thrown.
|
||||
- In case of structured types (array, object), the constructor behaves as similar versions for `std::vector` or
|
||||
`std::map`; that is, a JSON array or object is constructed from the values in the range.
|
||||
|
||||
8. Creates a copy of a given JSON value.
|
||||
|
||||
9. Move constructor. Constructs a JSON value with the contents of the given value `other` using move semantics. It
|
||||
"steals" the resources from `other` and leaves it as JSON `#!json null` value.
|
||||
|
||||
## Template parameters
|
||||
|
||||
`CompatibleType`
|
||||
: a type such that:
|
||||
|
||||
- `CompatibleType` is not derived from `std::istream`,
|
||||
- `CompatibleType` is not `basic_json` (to avoid hijacking copy/move constructors),
|
||||
- `CompatibleType` is not a different `basic_json` type (i.e. with different template arguments)
|
||||
- `CompatibleType` is not a `basic_json` nested type (e.g., `json_pointer`, `iterator`, etc.)
|
||||
- `json_serializer<U>` (with `U = uncvref_t<CompatibleType>`) has a `to_json(basic_json_t&, CompatibleType&&)`
|
||||
method
|
||||
|
||||
`BasicJsonType`:
|
||||
: a type such that:
|
||||
|
||||
- `BasicJsonType` is a `basic_json` type.
|
||||
- `BasicJsonType` has different template arguments than `basic_json_t`.
|
||||
|
||||
**Note:** For cross-`basic_json` conversions to produce correct results, the target `basic_json`'s
|
||||
`object_t::key_type` and `string_t` must be directly constructible from the source `basic_json`'s
|
||||
corresponding types. See the description of overload (4) above for details on what happens when
|
||||
this requirement is not met.
|
||||
|
||||
`U`:
|
||||
: `uncvref_t<CompatibleType>`
|
||||
|
||||
## Parameters
|
||||
|
||||
`v` (in)
|
||||
: the type of the value to create
|
||||
|
||||
`val` (in)
|
||||
: the value to be forwarded to the respective constructor
|
||||
|
||||
`init` (in)
|
||||
: initializer list with JSON values
|
||||
|
||||
`type_deduction` (in)
|
||||
: internal parameter; when set to `#!cpp true`, the type of the JSON value is deducted from the initializer list
|
||||
`init`; when set to `#!cpp false`, the type provided via `manual_type` is forced. This mode is used by the functions
|
||||
`array(initializer_list_t)` and `object(initializer_list_t)`.
|
||||
|
||||
`manual_type` (in)
|
||||
: internal parameter; when `type_deduction` is set to `#!cpp false`, the created JSON value will use the provided type
|
||||
(only `value_t::array` and `value_t::object` are valid); when `type_deduction` is set to `#!cpp true`, this
|
||||
parameter has no effect
|
||||
|
||||
`cnt` (in)
|
||||
: the number of JSON copies of `val` to create
|
||||
|
||||
`first` (in)
|
||||
: the beginning of the range to copy from (included)
|
||||
|
||||
`last` (in)
|
||||
: the end of the range to copy from (excluded)
|
||||
|
||||
`other` (in)
|
||||
: the JSON value to copy/move
|
||||
|
||||
## Exception safety
|
||||
|
||||
1. Strong guarantee: if an exception is thrown, there are no changes to any JSON value.
|
||||
2. No-throw guarantee: this constructor never throws exceptions.
|
||||
3. Depends on the called constructor. For types directly supported by the library (i.e., all types for which no
|
||||
`to_json()` function was provided), a strong guarantee holds: if an exception is thrown, there are no changes to any
|
||||
JSON value.
|
||||
4. Depends on the called constructor. For types directly supported by the library (i.e., all types for which no
|
||||
`to_json()` function was provided), a strong guarantee holds: if an exception is thrown, there are no changes to any
|
||||
JSON value.
|
||||
5. Strong guarantee: if an exception is thrown, there are no changes to any JSON value.
|
||||
6. Strong guarantee: if an exception is thrown, there are no changes to any JSON value.
|
||||
7. Strong guarantee: if an exception is thrown, there are no changes to any JSON value.
|
||||
8. Strong guarantee: if an exception is thrown, there are no changes to any JSON value.
|
||||
9. No-throw guarantee: this constructor never throws exceptions.
|
||||
|
||||
## Exceptions
|
||||
|
||||
1. (none)
|
||||
2. The function does not throw exceptions.
|
||||
3. (none)
|
||||
4. (none)
|
||||
5. The function can throw the following exceptions:
|
||||
- Throws [`type_error.301`](../../home/exceptions.md#jsonexceptiontype_error301) if `type_deduction` is
|
||||
`#!cpp false`, `manual_type` is `value_t::object`, but `init` contains an element which is not a pair whose first
|
||||
element is a string. In this case, the constructor could not create an object. If `type_deduction` would have been
|
||||
`#!cpp true`, an array would have been created. See `object(initializer_list_t)` for an example.
|
||||
6. (none)
|
||||
7. The function can throw the following exceptions:
|
||||
- Throws [`invalid_iterator.201`](../../home/exceptions.md#jsonexceptioninvalid_iterator201) if iterators `first`
|
||||
and `last` are not compatible (i.e., do not belong to the same JSON value). In this case, the range
|
||||
`[first, last)` is undefined.
|
||||
- Throws [`invalid_iterator.204`](../../home/exceptions.md#jsonexceptioninvalid_iterator204) if iterators `first`
|
||||
and `last` belong to a primitive type (number, boolean, or string), but `first` does not point to the first
|
||||
element anymore. In this case, the range `[first, last)` is undefined. See the example code below.
|
||||
- Throws [`invalid_iterator.206`](../../home/exceptions.md#jsonexceptioninvalid_iterator206) if iterators `first`
|
||||
and `last` belong to a `#!json null` value. In this case, the range `[first, last)` is undefined.
|
||||
8. (none)
|
||||
9. The function does not throw exceptions.
|
||||
|
||||
## Complexity
|
||||
|
||||
1. Constant.
|
||||
2. Constant.
|
||||
3. Usually linear in the size of the passed `val`, also depending on the implementation of the called `to_json()`
|
||||
method.
|
||||
4. Usually linear in the size of the passed `val`, also depending on the implementation of the called `to_json()`
|
||||
method.
|
||||
5. Linear in the size of the initializer list `init`.
|
||||
6. Linear in `cnt`.
|
||||
7. Linear in distance between `first` and `last`.
|
||||
8. Linear in the size of `other`.
|
||||
9. Constant.
|
||||
|
||||
## Notes
|
||||
|
||||
- Overload 5:
|
||||
|
||||
!!! note "Empty initializer list"
|
||||
|
||||
When used without parentheses around an empty initializer list, `basic_json()` is called instead of this
|
||||
function, yielding the JSON `#!json null` value.
|
||||
|
||||
- Overload 7:
|
||||
|
||||
!!! info "Preconditions"
|
||||
|
||||
- Iterators `first` and `last` must be initialized. **This precondition is enforced with a
|
||||
[runtime assertion](../../features/assertions.md).
|
||||
- Range `[first, last)` is valid. Usually, this precondition cannot be checked efficiently. Only certain edge
|
||||
cases are detected; see the description of the exceptions above. A violation of this precondition yields
|
||||
undefined behavior.
|
||||
|
||||
!!! danger "Runtime assertion"
|
||||
|
||||
A precondition is enforced with a [runtime assertion](../../features/assertions.md).
|
||||
|
||||
- Overload 8:
|
||||
|
||||
!!! info "Postcondition"
|
||||
|
||||
`#!cpp *this == other`
|
||||
|
||||
- Overload 9:
|
||||
|
||||
!!! info "Postconditions"
|
||||
|
||||
- `#!cpp `*this` has the same value as `other` before the call.
|
||||
- `other` is a JSON `#!json null` value
|
||||
|
||||
## Examples
|
||||
|
||||
??? example "Example: (1) create an empty value with a given type"
|
||||
|
||||
The following code shows the constructor for different `value_t` values.
|
||||
|
||||
```cpp
|
||||
--8<-- "examples/basic_json__value_t.cpp"
|
||||
```
|
||||
|
||||
Output:
|
||||
|
||||
```json
|
||||
--8<-- "examples/basic_json__value_t.output"
|
||||
```
|
||||
|
||||
??? example "Example: (2) create a `#!json null` object"
|
||||
|
||||
The following code shows the constructor with and without a null pointer parameter.
|
||||
|
||||
```cpp
|
||||
--8<-- "examples/basic_json__nullptr_t.cpp"
|
||||
```
|
||||
|
||||
Output:
|
||||
|
||||
```json
|
||||
--8<-- "examples/basic_json__nullptr_t.output"
|
||||
```
|
||||
|
||||
??? example "Example: (3) create a JSON value from compatible types"
|
||||
|
||||
The following code shows the constructor with several compatible types.
|
||||
|
||||
```cpp
|
||||
--8<-- "examples/basic_json__CompatibleType.cpp"
|
||||
```
|
||||
|
||||
Output:
|
||||
|
||||
```json
|
||||
--8<-- "examples/basic_json__CompatibleType.output"
|
||||
```
|
||||
|
||||
Note the output is platform-dependent.
|
||||
|
||||
??? example "Example: (5) create a container (array or object) from an initializer list"
|
||||
|
||||
The example below shows how JSON values are created from initializer lists.
|
||||
|
||||
```cpp
|
||||
--8<-- "examples/basic_json__list_init_t.cpp"
|
||||
```
|
||||
|
||||
Output:
|
||||
|
||||
```json
|
||||
--8<-- "examples/basic_json__list_init_t.output"
|
||||
```
|
||||
|
||||
??? example "Example: (6) construct an array with count copies of a given value"
|
||||
|
||||
The following code shows examples for creating arrays with several copies of a given value.
|
||||
|
||||
```cpp
|
||||
--8<-- "examples/basic_json__size_type_basic_json.cpp"
|
||||
```
|
||||
|
||||
Output:
|
||||
|
||||
```json
|
||||
--8<-- "examples/basic_json__size_type_basic_json.output"
|
||||
```
|
||||
|
||||
??? example "Example: (7) construct a JSON container given an iterator range"
|
||||
|
||||
The example below shows several ways to create JSON values by specifying a subrange with iterators.
|
||||
|
||||
```cpp
|
||||
--8<-- "examples/basic_json__InputIt_InputIt.cpp"
|
||||
```
|
||||
|
||||
Output:
|
||||
|
||||
```json
|
||||
--8<-- "examples/basic_json__InputIt_InputIt.output"
|
||||
```
|
||||
|
||||
??? example "Example: (8) copy constructor"
|
||||
|
||||
The following code shows an example for the copy constructor.
|
||||
|
||||
```cpp
|
||||
--8<-- "examples/basic_json__basic_json.cpp"
|
||||
```
|
||||
|
||||
Output:
|
||||
|
||||
```json
|
||||
--8<-- "examples/basic_json__basic_json.output"
|
||||
```
|
||||
|
||||
??? example "Example: (9) move constructor"
|
||||
|
||||
The code below shows the move constructor explicitly called via `std::move`.
|
||||
|
||||
```cpp
|
||||
--8<-- "examples/basic_json__moveconstructor.cpp"
|
||||
```
|
||||
|
||||
Output:
|
||||
|
||||
```json
|
||||
--8<-- "examples/basic_json__moveconstructor.output"
|
||||
```
|
||||
|
||||
## Version history
|
||||
|
||||
1. Since version 1.0.0.
|
||||
2. Since version 1.0.0.
|
||||
3. Since version 2.1.0.
|
||||
4. Since version 3.2.0.
|
||||
5. Since version 1.0.0.
|
||||
6. Since version 1.0.0.
|
||||
7. Since version 1.0.0.
|
||||
8. Since version 1.0.0.
|
||||
9. Since version 1.0.0.
|
||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1,768 @@
|
||||
# nlohmann::basic_json::basic_json
|
||||
|
||||
```
|
||||
// (1)
|
||||
basic_json(const value_t v);
|
||||
|
||||
// (2)
|
||||
basic_json(std::nullptr_t = nullptr) noexcept;
|
||||
|
||||
// (3)
|
||||
template<typename CompatibleType>
|
||||
basic_json(CompatibleType&& val) noexcept(noexcept(
|
||||
JSONSerializer<U>::to_json(std::declval<basic_json_t&>(),
|
||||
std::forward<CompatibleType>(val))));
|
||||
|
||||
// (4)
|
||||
template<typename BasicJsonType>
|
||||
basic_json(const BasicJsonType& val);
|
||||
|
||||
// (5)
|
||||
basic_json(initializer_list_t init,
|
||||
bool type_deduction = true,
|
||||
value_t manual_type = value_t::array);
|
||||
|
||||
// (6)
|
||||
basic_json(size_type cnt, const basic_json& val);
|
||||
|
||||
// (7)
|
||||
basic_json(iterator first, iterator last);
|
||||
basic_json(const_iterator first, const_iterator last);
|
||||
|
||||
// (8)
|
||||
basic_json(const basic_json& other);
|
||||
|
||||
// (9)
|
||||
basic_json(basic_json&& other) noexcept;
|
||||
```
|
||||
|
||||
1. Create an empty JSON value with a given type. The value will be default initialized with an empty value which depends on the type:
|
||||
|
||||
| Value type | initial value |
|
||||
| ---------- | ------------- |
|
||||
| null | `null` |
|
||||
| boolean | `false` |
|
||||
| string | `""` |
|
||||
| number | `0` |
|
||||
| object | `{}` |
|
||||
| array | `[]` |
|
||||
| binary | empty array |
|
||||
|
||||
The postcondition of this constructor can be restored by calling [`clear()`](https://json.nlohmann.me/api/basic_json/clear/index.md).
|
||||
|
||||
1. Create a `null` JSON value. It either takes a null pointer as parameter (explicitly creating `null`) or no parameter (implicitly creating `null`). The passed null pointer itself is not read -- it is only used to choose the right constructor.
|
||||
|
||||
1. This is a "catch all" constructor for all compatible JSON types; that is, types for which a `to_json()` method exists. The constructor forwards the parameter `val` to that method (to `json_serializer<U>::to_json` method with `U = uncvref_t<CompatibleType>`, to be exact).
|
||||
|
||||
Template type `CompatibleType` includes, but is not limited to, the following types:
|
||||
|
||||
- **arrays**: [`array_t`](https://json.nlohmann.me/api/basic_json/array_t/index.md) and all kinds of compatible containers such as `std::vector`, `std::deque`, `std::list`, `std::forward_list`, `std::array`, `std::valarray`, `std::set`, `std::unordered_set`, `std::multiset`, and `std::unordered_multiset` with a `value_type` from which a `basic_json` value can be constructed.
|
||||
- **objects**: [`object_t`](https://json.nlohmann.me/api/basic_json/object_t/index.md) and all kinds of compatible associative containers such as `std::map`, `std::unordered_map`, `std::multimap`, and `std::unordered_multimap` with a `key_type` compatible to `string_t` and a `value_type` from which a `basic_json` value can be constructed.
|
||||
- **strings**: `string_t`, string literals, and all compatible string containers can be used.
|
||||
- **numbers**: [`number_integer_t`](https://json.nlohmann.me/api/basic_json/number_integer_t/index.md), [`number_unsigned_t`](https://json.nlohmann.me/api/basic_json/number_unsigned_t/index.md), [`number_float_t`](https://json.nlohmann.me/api/basic_json/number_float_t/index.md), and all convertible number types such as `int`, `size_t`, `int64_t`, `float` or `double` can be used.
|
||||
- **boolean**: `boolean_t` / `bool` can be used.
|
||||
- **binary**: `binary_t` / `std::vector<uint8_t>` may be used; unfortunately because string literals cannot be distinguished from binary character arrays by the C++ type system, all types compatible with `const char*` will be directed to the string constructor instead. This is both for backwards compatibility and due to the fact that a binary type is not a standard JSON type.
|
||||
|
||||
See the examples below.
|
||||
|
||||
1. This is a constructor for existing `basic_json` types. It does not hijack copy/move constructors, since the parameter has different template arguments than the current ones.
|
||||
|
||||
The constructor tries to convert the internal `m_value` of the parameter. Each member value (object, array, string, etc.) is serialized via the corresponding `to_json()` overload. For objects and strings, the conversion requires that the *target* `basic_json` type's `object_t::key_type` (or `string_t`) be directly constructible from the *source* type's corresponding member type via `is_constructible`. If this requirement is not met, the conversion does not fail to compile; instead, it silently falls back to the array-conversion path, which represents objects as arrays of `[key, value]` pairs and strings as arrays of character codes. This is a known limitation tracked in [issue #3425](https://github.com/nlohmann/json/issues/3425).
|
||||
|
||||
1. Creates a JSON value of type array or object from the passed initializer list `init`. In case `type_deduction` is `true` (default), the type of the JSON value to be created is deducted from the initializer list `init` according to the following rules:
|
||||
|
||||
1. If the list is empty, an empty JSON object value `{}` is created.
|
||||
1. If the list consists of pairs whose first element is a string, a JSON object value is created where the first elements of the pairs are treated as keys and the second elements are as values.
|
||||
1. In all other cases, an array is created.
|
||||
|
||||
The rules aim to create the best fit between a C++ initializer list and JSON values. The rationale is as follows:
|
||||
|
||||
1. The empty initializer list is written as `{}` which is exactly an empty JSON object.
|
||||
1. C++ has no way of describing mapped types other than to list a list of pairs. As JSON requires that keys must be of type string, rule 2 is the weakest constraint one can pose on initializer lists to interpret them as an object.
|
||||
1. In all other cases, the initializer list could not be interpreted as a JSON object type, so interpreting it as a JSON array type is safe.
|
||||
|
||||
With the rules described above, the following JSON values cannot be expressed by an initializer list:
|
||||
|
||||
- the empty array (`[]`): use `array(initializer_list_t)` with an empty initializer list in this case
|
||||
- arrays whose elements satisfy rule 2: use `array(initializer_list_t)` with the same initializer list in this case
|
||||
|
||||
Function [`array()`](https://json.nlohmann.me/api/basic_json/array/index.md) and [`object()`](https://json.nlohmann.me/api/basic_json/object/index.md) force array and object creation from initializer lists, respectively.
|
||||
|
||||
Brace initialization yields arrays
|
||||
|
||||
Because this constructor takes an `initializer_list_t`, brace-initializing a `json`/`ordered_json` from another `json` value wraps it in a single-element array rather than copying it:
|
||||
|
||||
```
|
||||
json j1 = "hello";
|
||||
json j2{j1}; // [!] j2 is ["hello"], NOT a copy of j1
|
||||
json j3(j1); // j3 is "hello" -- parentheses copy as expected
|
||||
```
|
||||
|
||||
See the FAQ entry on [brace initialization](https://json.nlohmann.me/home/faq/#brace-initialization-yields-arrays) for the full explanation, an opt-in macro to change this behavior, and how to explicitly create a single-element array (`json::array({value})`) if that is what you want.
|
||||
|
||||
1. Constructs a JSON array value by creating `cnt` copies of a passed value. In case `cnt` is `0`, an empty array is created.
|
||||
|
||||
1. Constructs the JSON value with the contents of the range `[first, last)`. The semantics depend on the different types a JSON value can have:
|
||||
|
||||
- In case of a `null` type, [invalid_iterator.206](https://json.nlohmann.me/home/exceptions/#jsonexceptioninvalid_iterator206) is thrown.
|
||||
- In case of other primitive types (number, boolean, or string), `first` must be `begin()` and `last` must be `end()`. In this case, the value is copied. Otherwise, [`invalid_iterator.204`](https://json.nlohmann.me/home/exceptions/#jsonexceptioninvalid_iterator204) is thrown.
|
||||
- In case of structured types (array, object), the constructor behaves as similar versions for `std::vector` or `std::map`; that is, a JSON array or object is constructed from the values in the range.
|
||||
|
||||
1. Creates a copy of a given JSON value.
|
||||
|
||||
1. Move constructor. Constructs a JSON value with the contents of the given value `other` using move semantics. It "steals" the resources from `other` and leaves it as JSON `null` value.
|
||||
|
||||
## Template parameters
|
||||
|
||||
`CompatibleType` : a type such that:
|
||||
|
||||
```
|
||||
- `CompatibleType` is not derived from `std::istream`,
|
||||
- `CompatibleType` is not `basic_json` (to avoid hijacking copy/move constructors),
|
||||
- `CompatibleType` is not a different `basic_json` type (i.e. with different template arguments)
|
||||
- `CompatibleType` is not a `basic_json` nested type (e.g., `json_pointer`, `iterator`, etc.)
|
||||
- `json_serializer<U>` (with `U = uncvref_t<CompatibleType>`) has a `to_json(basic_json_t&, CompatibleType&&)`
|
||||
method
|
||||
```
|
||||
|
||||
`BasicJsonType`: : a type such that:
|
||||
|
||||
```
|
||||
- `BasicJsonType` is a `basic_json` type.
|
||||
- `BasicJsonType` has different template arguments than `basic_json_t`.
|
||||
|
||||
**Note:** For cross-`basic_json` conversions to produce correct results, the target `basic_json`'s
|
||||
`object_t::key_type` and `string_t` must be directly constructible from the source `basic_json`'s
|
||||
corresponding types. See the description of overload (4) above for details on what happens when
|
||||
this requirement is not met.
|
||||
```
|
||||
|
||||
`U`: : `uncvref_t<CompatibleType>`
|
||||
|
||||
## Parameters
|
||||
|
||||
`v` (in) : the type of the value to create
|
||||
|
||||
`val` (in) : the value to be forwarded to the respective constructor
|
||||
|
||||
`init` (in) : initializer list with JSON values
|
||||
|
||||
`type_deduction` (in) : internal parameter; when set to `true`, the type of the JSON value is deducted from the initializer list `init`; when set to `false`, the type provided via `manual_type` is forced. This mode is used by the functions `array(initializer_list_t)` and `object(initializer_list_t)`.
|
||||
|
||||
`manual_type` (in) : internal parameter; when `type_deduction` is set to `false`, the created JSON value will use the provided type (only `value_t::array` and `value_t::object` are valid); when `type_deduction` is set to `true`, this parameter has no effect
|
||||
|
||||
`cnt` (in) : the number of JSON copies of `val` to create
|
||||
|
||||
`first` (in) : the beginning of the range to copy from (included)
|
||||
|
||||
`last` (in) : the end of the range to copy from (excluded)
|
||||
|
||||
`other` (in) : the JSON value to copy/move
|
||||
|
||||
## Exception safety
|
||||
|
||||
1. Strong guarantee: if an exception is thrown, there are no changes to any JSON value.
|
||||
1. No-throw guarantee: this constructor never throws exceptions.
|
||||
1. Depends on the called constructor. For types directly supported by the library (i.e., all types for which no `to_json()` function was provided), a strong guarantee holds: if an exception is thrown, there are no changes to any JSON value.
|
||||
1. Depends on the called constructor. For types directly supported by the library (i.e., all types for which no `to_json()` function was provided), a strong guarantee holds: if an exception is thrown, there are no changes to any JSON value.
|
||||
1. Strong guarantee: if an exception is thrown, there are no changes to any JSON value.
|
||||
1. Strong guarantee: if an exception is thrown, there are no changes to any JSON value.
|
||||
1. Strong guarantee: if an exception is thrown, there are no changes to any JSON value.
|
||||
1. Strong guarantee: if an exception is thrown, there are no changes to any JSON value.
|
||||
1. No-throw guarantee: this constructor never throws exceptions.
|
||||
|
||||
## Exceptions
|
||||
|
||||
1. (none)
|
||||
1. The function does not throw exceptions.
|
||||
1. (none)
|
||||
1. (none)
|
||||
1. The function can throw the following exceptions:
|
||||
- Throws [`type_error.301`](https://json.nlohmann.me/home/exceptions/#jsonexceptiontype_error301) if `type_deduction` is `false`, `manual_type` is `value_t::object`, but `init` contains an element which is not a pair whose first element is a string. In this case, the constructor could not create an object. If `type_deduction` would have been `true`, an array would have been created. See `object(initializer_list_t)` for an example.
|
||||
1. (none)
|
||||
1. The function can throw the following exceptions:
|
||||
- Throws [`invalid_iterator.201`](https://json.nlohmann.me/home/exceptions/#jsonexceptioninvalid_iterator201) if iterators `first` and `last` are not compatible (i.e., do not belong to the same JSON value). In this case, the range `[first, last)` is undefined.
|
||||
- Throws [`invalid_iterator.204`](https://json.nlohmann.me/home/exceptions/#jsonexceptioninvalid_iterator204) if iterators `first` and `last` belong to a primitive type (number, boolean, or string), but `first` does not point to the first element anymore. In this case, the range `[first, last)` is undefined. See the example code below.
|
||||
- Throws [`invalid_iterator.206`](https://json.nlohmann.me/home/exceptions/#jsonexceptioninvalid_iterator206) if iterators `first` and `last` belong to a `null` value. In this case, the range `[first, last)` is undefined.
|
||||
1. (none)
|
||||
1. The function does not throw exceptions.
|
||||
|
||||
## Complexity
|
||||
|
||||
1. Constant.
|
||||
1. Constant.
|
||||
1. Usually linear in the size of the passed `val`, also depending on the implementation of the called `to_json()` method.
|
||||
1. Usually linear in the size of the passed `val`, also depending on the implementation of the called `to_json()` method.
|
||||
1. Linear in the size of the initializer list `init`.
|
||||
1. Linear in `cnt`.
|
||||
1. Linear in distance between `first` and `last`.
|
||||
1. Linear in the size of `other`.
|
||||
1. Constant.
|
||||
|
||||
## Notes
|
||||
|
||||
- Overload 5:
|
||||
|
||||
Empty initializer list
|
||||
|
||||
When used without parentheses around an empty initializer list, `basic_json()` is called instead of this function, yielding the JSON `null` value.
|
||||
|
||||
- Overload 7:
|
||||
|
||||
Preconditions
|
||||
|
||||
- Iterators `first` and `last` must be initialized. \*\*This precondition is enforced with a [runtime assertion](https://json.nlohmann.me/features/assertions/index.md).
|
||||
- Range `[first, last)` is valid. Usually, this precondition cannot be checked efficiently. Only certain edge cases are detected; see the description of the exceptions above. A violation of this precondition yields undefined behavior.
|
||||
|
||||
Runtime assertion
|
||||
|
||||
A precondition is enforced with a [runtime assertion](https://json.nlohmann.me/features/assertions/index.md).
|
||||
|
||||
- Overload 8:
|
||||
|
||||
Postcondition
|
||||
|
||||
`*this == other`
|
||||
|
||||
- Overload 9:
|
||||
|
||||
Postconditions
|
||||
|
||||
- `` `*this `` has the same value as `other` before the call.
|
||||
- `other` is a JSON `null` value
|
||||
|
||||
## Examples
|
||||
|
||||
Example: (1) create an empty value with a given type
|
||||
|
||||
The following code shows the constructor for different `value_t` values.
|
||||
|
||||
```
|
||||
#include <iostream>
|
||||
#include <nlohmann/json.hpp>
|
||||
|
||||
using json = nlohmann::json;
|
||||
|
||||
int main()
|
||||
{
|
||||
// create the different JSON values with default values
|
||||
json j_null(json::value_t::null);
|
||||
json j_boolean(json::value_t::boolean);
|
||||
json j_number_integer(json::value_t::number_integer);
|
||||
json j_number_float(json::value_t::number_float);
|
||||
json j_object(json::value_t::object);
|
||||
json j_array(json::value_t::array);
|
||||
json j_string(json::value_t::string);
|
||||
|
||||
// serialize the JSON values
|
||||
std::cout << j_null << '\n';
|
||||
std::cout << j_boolean << '\n';
|
||||
std::cout << j_number_integer << '\n';
|
||||
std::cout << j_number_float << '\n';
|
||||
std::cout << j_object << '\n';
|
||||
std::cout << j_array << '\n';
|
||||
std::cout << j_string << '\n';
|
||||
}
|
||||
```
|
||||
|
||||
Output:
|
||||
|
||||
```
|
||||
null
|
||||
false
|
||||
0
|
||||
0.0
|
||||
{}
|
||||
[]
|
||||
""
|
||||
```
|
||||
|
||||
Example: (2) create a `null` object
|
||||
|
||||
The following code shows the constructor with and without a null pointer parameter.
|
||||
|
||||
```
|
||||
#include <iostream>
|
||||
#include <nlohmann/json.hpp>
|
||||
|
||||
using json = nlohmann::json;
|
||||
|
||||
int main()
|
||||
{
|
||||
// implicitly create a JSON null value
|
||||
json j1;
|
||||
|
||||
// explicitly create a JSON null value
|
||||
json j2(nullptr);
|
||||
|
||||
// serialize the JSON null value
|
||||
std::cout << j1 << '\n' << j2 << '\n';
|
||||
}
|
||||
```
|
||||
|
||||
Output:
|
||||
|
||||
```
|
||||
null
|
||||
null
|
||||
```
|
||||
|
||||
Example: (3) create a JSON value from compatible types
|
||||
|
||||
The following code shows the constructor with several compatible types.
|
||||
|
||||
```
|
||||
#include <iostream>
|
||||
#include <deque>
|
||||
#include <list>
|
||||
#include <forward_list>
|
||||
#include <set>
|
||||
#include <unordered_map>
|
||||
#include <unordered_set>
|
||||
#include <valarray>
|
||||
#include <nlohmann/json.hpp>
|
||||
|
||||
using json = nlohmann::json;
|
||||
|
||||
int main()
|
||||
{
|
||||
// ============
|
||||
// object types
|
||||
// ============
|
||||
|
||||
// create an object from an object_t value
|
||||
json::object_t object_value = { {"one", 1}, {"two", 2} };
|
||||
json j_object_t(object_value);
|
||||
|
||||
// create an object from std::map
|
||||
std::map<std::string, int> c_map
|
||||
{
|
||||
{"one", 1}, {"two", 2}, {"three", 3}
|
||||
};
|
||||
json j_map(c_map);
|
||||
|
||||
// create an object from std::unordered_map
|
||||
std::unordered_map<const char*, double> c_umap
|
||||
{
|
||||
{"one", 1.2}, {"two", 2.3}, {"three", 3.4}
|
||||
};
|
||||
json j_umap(c_umap);
|
||||
|
||||
// create an object from std::multimap
|
||||
std::multimap<std::string, bool> c_mmap
|
||||
{
|
||||
{"one", true}, {"two", true}, {"three", false}, {"three", true}
|
||||
};
|
||||
json j_mmap(c_mmap); // only one entry for key "three" is used
|
||||
|
||||
// create an object from std::unordered_multimap
|
||||
std::unordered_multimap<std::string, bool> c_ummap
|
||||
{
|
||||
{"one", true}, {"two", true}, {"three", false}, {"three", true}
|
||||
};
|
||||
json j_ummap(c_ummap); // only one entry for key "three" is used
|
||||
|
||||
// serialize the JSON objects
|
||||
std::cout << j_object_t << '\n';
|
||||
std::cout << j_map << '\n';
|
||||
std::cout << j_umap << '\n';
|
||||
std::cout << j_mmap << '\n';
|
||||
std::cout << j_ummap << "\n\n";
|
||||
|
||||
// ===========
|
||||
// array types
|
||||
// ===========
|
||||
|
||||
// create an array from an array_t value
|
||||
json::array_t array_value = {"one", "two", 3, 4.5, false};
|
||||
json j_array_t(array_value);
|
||||
|
||||
// create an array from std::vector
|
||||
std::vector<int> c_vector {1, 2, 3, 4};
|
||||
json j_vec(c_vector);
|
||||
|
||||
// create an array from std::valarray
|
||||
std::valarray<short> c_valarray {10, 9, 8, 7};
|
||||
json j_valarray(c_valarray);
|
||||
|
||||
// create an array from std::deque
|
||||
std::deque<double> c_deque {1.2, 2.3, 3.4, 5.6};
|
||||
json j_deque(c_deque);
|
||||
|
||||
// create an array from std::list
|
||||
std::list<bool> c_list {true, true, false, true};
|
||||
json j_list(c_list);
|
||||
|
||||
// create an array from std::forward_list
|
||||
std::forward_list<std::int64_t> c_flist {12345678909876, 23456789098765, 34567890987654, 45678909876543};
|
||||
json j_flist(c_flist);
|
||||
|
||||
// create an array from std::array
|
||||
std::array<unsigned long, 4> c_array {{1, 2, 3, 4}};
|
||||
json j_array(c_array);
|
||||
|
||||
// create an array from std::set
|
||||
std::set<std::string> c_set {"one", "two", "three", "four", "one"};
|
||||
json j_set(c_set); // only one entry for "one" is used
|
||||
|
||||
// create an array from std::unordered_set
|
||||
std::unordered_set<std::string> c_uset {"one", "two", "three", "four", "one"};
|
||||
json j_uset(c_uset); // only one entry for "one" is used
|
||||
|
||||
// create an array from std::multiset
|
||||
std::multiset<std::string> c_mset {"one", "two", "one", "four"};
|
||||
json j_mset(c_mset); // both entries for "one" are used
|
||||
|
||||
// create an array from std::unordered_multiset
|
||||
std::unordered_multiset<std::string> c_umset {"one", "two", "one", "four"};
|
||||
json j_umset(c_umset); // both entries for "one" are used
|
||||
|
||||
// serialize the JSON arrays
|
||||
std::cout << j_array_t << '\n';
|
||||
std::cout << j_vec << '\n';
|
||||
std::cout << j_valarray << '\n';
|
||||
std::cout << j_deque << '\n';
|
||||
std::cout << j_list << '\n';
|
||||
std::cout << j_flist << '\n';
|
||||
std::cout << j_array << '\n';
|
||||
std::cout << j_set << '\n';
|
||||
std::cout << j_uset << '\n';
|
||||
std::cout << j_mset << '\n';
|
||||
std::cout << j_umset << "\n\n";
|
||||
|
||||
// ============
|
||||
// string types
|
||||
// ============
|
||||
|
||||
// create string from a string_t value
|
||||
json::string_t string_value = "The quick brown fox jumps over the lazy dog.";
|
||||
json j_string_t(string_value);
|
||||
|
||||
// create a JSON string directly from a string literal
|
||||
json j_string_literal("The quick brown fox jumps over the lazy dog.");
|
||||
|
||||
// create string from std::string
|
||||
std::string s_stdstring = "The quick brown fox jumps over the lazy dog.";
|
||||
json j_stdstring(s_stdstring);
|
||||
|
||||
// serialize the JSON strings
|
||||
std::cout << j_string_t << '\n';
|
||||
std::cout << j_string_literal << '\n';
|
||||
std::cout << j_stdstring << "\n\n";
|
||||
|
||||
// ============
|
||||
// number types
|
||||
// ============
|
||||
|
||||
// create a JSON number from number_integer_t
|
||||
json::number_integer_t value_integer_t = -42;
|
||||
json j_integer_t(value_integer_t);
|
||||
|
||||
// create a JSON number from number_unsigned_t
|
||||
json::number_integer_t value_unsigned_t = 17;
|
||||
json j_unsigned_t(value_unsigned_t);
|
||||
|
||||
// create a JSON number from an anonymous enum
|
||||
enum { enum_value = 17 };
|
||||
json j_enum(enum_value);
|
||||
|
||||
// create values of different integer types
|
||||
short n_short = 42;
|
||||
int n_int = -23;
|
||||
long n_long = 1024;
|
||||
int_least32_t n_int_least32_t = -17;
|
||||
uint8_t n_uint8_t = 8;
|
||||
|
||||
// create (integer) JSON numbers
|
||||
json j_short(n_short);
|
||||
json j_int(n_int);
|
||||
json j_long(n_long);
|
||||
json j_int_least32_t(n_int_least32_t);
|
||||
json j_uint8_t(n_uint8_t);
|
||||
|
||||
// create values of different floating-point types
|
||||
json::number_float_t v_ok = 3.141592653589793;
|
||||
json::number_float_t v_nan = NAN;
|
||||
json::number_float_t v_infinity = INFINITY;
|
||||
|
||||
// create values of different floating-point types
|
||||
float n_float = 42.23;
|
||||
float n_float_nan = 1.0f / 0.0f;
|
||||
double n_double = 23.42;
|
||||
|
||||
// create (floating point) JSON numbers
|
||||
json j_ok(v_ok);
|
||||
json j_nan(v_nan);
|
||||
json j_infinity(v_infinity);
|
||||
json j_float(n_float);
|
||||
json j_float_nan(n_float_nan);
|
||||
json j_double(n_double);
|
||||
|
||||
// serialize the JSON numbers
|
||||
std::cout << j_integer_t << '\n';
|
||||
std::cout << j_unsigned_t << '\n';
|
||||
std::cout << j_enum << '\n';
|
||||
std::cout << j_short << '\n';
|
||||
std::cout << j_int << '\n';
|
||||
std::cout << j_long << '\n';
|
||||
std::cout << j_int_least32_t << '\n';
|
||||
std::cout << j_uint8_t << '\n';
|
||||
std::cout << j_ok << '\n';
|
||||
std::cout << j_nan << '\n';
|
||||
std::cout << j_infinity << '\n';
|
||||
std::cout << j_float << '\n';
|
||||
std::cout << j_float_nan << '\n';
|
||||
std::cout << j_double << "\n\n";
|
||||
|
||||
// =============
|
||||
// boolean types
|
||||
// =============
|
||||
|
||||
// create boolean values
|
||||
json j_truth = true;
|
||||
json j_falsity = false;
|
||||
|
||||
// serialize the JSON booleans
|
||||
std::cout << j_truth << '\n';
|
||||
std::cout << j_falsity << '\n';
|
||||
}
|
||||
```
|
||||
|
||||
Output:
|
||||
|
||||
```
|
||||
{"one":1,"two":2}
|
||||
{"one":1,"three":3,"two":2}
|
||||
{"one":1.2,"three":3.4,"two":2.3}
|
||||
{"one":true,"three":false,"two":true}
|
||||
{"one":true,"three":false,"two":true}
|
||||
|
||||
["one","two",3,4.5,false]
|
||||
[1,2,3,4]
|
||||
[10,9,8,7]
|
||||
[1.2,2.3,3.4,5.6]
|
||||
[true,true,false,true]
|
||||
[12345678909876,23456789098765,34567890987654,45678909876543]
|
||||
[1,2,3,4]
|
||||
["four","one","three","two"]
|
||||
["four","three","two","one"]
|
||||
["four","one","one","two"]
|
||||
["four","two","one","one"]
|
||||
|
||||
"The quick brown fox jumps over the lazy dog."
|
||||
"The quick brown fox jumps over the lazy dog."
|
||||
"The quick brown fox jumps over the lazy dog."
|
||||
|
||||
-42
|
||||
17
|
||||
17
|
||||
42
|
||||
-23
|
||||
1024
|
||||
-17
|
||||
8
|
||||
3.141592653589793
|
||||
null
|
||||
null
|
||||
42.22999954223633
|
||||
null
|
||||
23.42
|
||||
|
||||
true
|
||||
false
|
||||
```
|
||||
|
||||
Note the output is platform-dependent.
|
||||
|
||||
Example: (5) create a container (array or object) from an initializer list
|
||||
|
||||
The example below shows how JSON values are created from initializer lists.
|
||||
|
||||
```
|
||||
#include <iostream>
|
||||
#include <nlohmann/json.hpp>
|
||||
|
||||
using json = nlohmann::json;
|
||||
|
||||
int main()
|
||||
{
|
||||
// create JSON values
|
||||
json j_empty_init_list = json({});
|
||||
json j_object = { {"one", 1}, {"two", 2} };
|
||||
json j_array = {1, 2, 3, 4};
|
||||
json j_nested_object = { {"one", {1}}, {"two", {1, 2}} };
|
||||
json j_nested_array = { {{1}, "one"}, {{1, 2}, "two"} };
|
||||
|
||||
// serialize the JSON value
|
||||
std::cout << j_empty_init_list << '\n';
|
||||
std::cout << j_object << '\n';
|
||||
std::cout << j_array << '\n';
|
||||
std::cout << j_nested_object << '\n';
|
||||
std::cout << j_nested_array << '\n';
|
||||
}
|
||||
```
|
||||
|
||||
Output:
|
||||
|
||||
```
|
||||
{}
|
||||
{"one":1,"two":2}
|
||||
[1,2,3,4]
|
||||
{"one":[1],"two":[1,2]}
|
||||
[[[1],"one"],[[1,2],"two"]]
|
||||
```
|
||||
|
||||
Example: (6) construct an array with count copies of a given value
|
||||
|
||||
The following code shows examples for creating arrays with several copies of a given value.
|
||||
|
||||
```
|
||||
#include <iostream>
|
||||
#include <nlohmann/json.hpp>
|
||||
|
||||
using json = nlohmann::json;
|
||||
|
||||
int main()
|
||||
{
|
||||
// create an array by creating copies of a JSON value
|
||||
json value = "Hello";
|
||||
json array_0 = json(0, value);
|
||||
json array_1 = json(1, value);
|
||||
json array_5 = json(5, value);
|
||||
|
||||
// serialize the JSON arrays
|
||||
std::cout << array_0 << '\n';
|
||||
std::cout << array_1 << '\n';
|
||||
std::cout << array_5 << '\n';
|
||||
}
|
||||
```
|
||||
|
||||
Output:
|
||||
|
||||
```
|
||||
[]
|
||||
["Hello"]
|
||||
["Hello","Hello","Hello","Hello","Hello"]
|
||||
```
|
||||
|
||||
Example: (7) construct a JSON container given an iterator range
|
||||
|
||||
The example below shows several ways to create JSON values by specifying a subrange with iterators.
|
||||
|
||||
```
|
||||
#include <iostream>
|
||||
#include <nlohmann/json.hpp>
|
||||
|
||||
using json = nlohmann::json;
|
||||
|
||||
int main()
|
||||
{
|
||||
// create JSON values
|
||||
json j_array = {"alpha", "bravo", "charly", "delta", "easy"};
|
||||
json j_number = 42;
|
||||
json j_object = {{"one", "eins"}, {"two", "zwei"}};
|
||||
|
||||
// create copies using iterators
|
||||
json j_array_range(j_array.begin() + 1, j_array.end() - 2);
|
||||
json j_number_range(j_number.begin(), j_number.end());
|
||||
json j_object_range(j_object.begin(), j_object.find("two"));
|
||||
|
||||
// serialize the values
|
||||
std::cout << j_array_range << '\n';
|
||||
std::cout << j_number_range << '\n';
|
||||
std::cout << j_object_range << '\n';
|
||||
|
||||
// example for an exception
|
||||
try
|
||||
{
|
||||
json j_invalid(j_number.begin() + 1, j_number.end());
|
||||
}
|
||||
catch (const json::invalid_iterator& e)
|
||||
{
|
||||
std::cout << e.what() << '\n';
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Output:
|
||||
|
||||
```
|
||||
["bravo","charly"]
|
||||
42
|
||||
{"one":"eins"}
|
||||
[json.exception.invalid_iterator.204] iterators out of range
|
||||
```
|
||||
|
||||
Example: (8) copy constructor
|
||||
|
||||
The following code shows an example for the copy constructor.
|
||||
|
||||
```
|
||||
#include <iostream>
|
||||
#include <nlohmann/json.hpp>
|
||||
|
||||
using json = nlohmann::json;
|
||||
|
||||
int main()
|
||||
{
|
||||
// create a JSON array
|
||||
json j1 = {"one", "two", 3, 4.5, false};
|
||||
|
||||
// create a copy
|
||||
json j2(j1);
|
||||
|
||||
// serialize the JSON array
|
||||
std::cout << j1 << " = " << j2 << '\n';
|
||||
std::cout << std::boolalpha << (j1 == j2) << '\n';
|
||||
}
|
||||
```
|
||||
|
||||
Output:
|
||||
|
||||
```
|
||||
["one","two",3,4.5,false] = ["one","two",3,4.5,false]
|
||||
true
|
||||
```
|
||||
|
||||
Example: (9) move constructor
|
||||
|
||||
The code below shows the move constructor explicitly called via `std::move`.
|
||||
|
||||
```
|
||||
#include <iostream>
|
||||
#include <nlohmann/json.hpp>
|
||||
|
||||
using json = nlohmann::json;
|
||||
|
||||
int main()
|
||||
{
|
||||
// create a JSON value
|
||||
json a = 23;
|
||||
|
||||
// move contents of a to b
|
||||
json b(std::move(a));
|
||||
|
||||
// serialize the JSON arrays
|
||||
std::cout << a << '\n';
|
||||
std::cout << b << '\n';
|
||||
}
|
||||
```
|
||||
|
||||
Output:
|
||||
|
||||
```
|
||||
null
|
||||
23
|
||||
```
|
||||
|
||||
## Version history
|
||||
|
||||
1. Since version 1.0.0.
|
||||
1. Since version 1.0.0.
|
||||
1. Since version 2.1.0.
|
||||
1. Since version 3.2.0.
|
||||
1. Since version 1.0.0.
|
||||
1. Since version 1.0.0.
|
||||
1. Since version 1.0.0.
|
||||
1. Since version 1.0.0.
|
||||
1. Since version 1.0.0.
|
||||
@@ -0,0 +1,42 @@
|
||||
# <small>nlohmann::basic_json::</small>begin
|
||||
|
||||
```cpp
|
||||
iterator begin() noexcept;
|
||||
const_iterator begin() const noexcept;
|
||||
```
|
||||
|
||||
Returns an iterator to the first element.
|
||||
|
||||

|
||||
|
||||
## Return value
|
||||
|
||||
iterator to the first element
|
||||
|
||||
## Exception safety
|
||||
|
||||
No-throw guarantee: this member function never throws exceptions.
|
||||
|
||||
## Complexity
|
||||
|
||||
Constant.
|
||||
|
||||
## Examples
|
||||
|
||||
??? example
|
||||
|
||||
The following code shows an example for `begin()`.
|
||||
|
||||
```cpp
|
||||
--8<-- "examples/begin.cpp"
|
||||
```
|
||||
|
||||
Output:
|
||||
|
||||
```json
|
||||
--8<-- "examples/begin.output"
|
||||
```
|
||||
|
||||
## Version history
|
||||
|
||||
- Added in version 1.0.0.
|
||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1,55 @@
|
||||
# nlohmann::basic_json::begin
|
||||
|
||||
```
|
||||
iterator begin() noexcept;
|
||||
const_iterator begin() const noexcept;
|
||||
```
|
||||
|
||||
Returns an iterator to the first element.
|
||||
|
||||
## Return value
|
||||
|
||||
iterator to the first element
|
||||
|
||||
## Exception safety
|
||||
|
||||
No-throw guarantee: this member function never throws exceptions.
|
||||
|
||||
## Complexity
|
||||
|
||||
Constant.
|
||||
|
||||
## Examples
|
||||
|
||||
Example
|
||||
|
||||
The following code shows an example for `begin()`.
|
||||
|
||||
```
|
||||
#include <iostream>
|
||||
#include <nlohmann/json.hpp>
|
||||
|
||||
using json = nlohmann::json;
|
||||
|
||||
int main()
|
||||
{
|
||||
// create an array value
|
||||
json array = {1, 2, 3, 4, 5};
|
||||
|
||||
// get an iterator to the first element
|
||||
json::iterator it = array.begin();
|
||||
|
||||
// serialize the element that the iterator points to
|
||||
std::cout << *it << '\n';
|
||||
}
|
||||
```
|
||||
|
||||
Output:
|
||||
|
||||
```
|
||||
1
|
||||
```
|
||||
|
||||
## Version history
|
||||
|
||||
- Added in version 1.0.0.
|
||||
@@ -0,0 +1,66 @@
|
||||
# <small>nlohmann::basic_json::</small>binary
|
||||
|
||||
```cpp
|
||||
// (1)
|
||||
static basic_json binary(const typename binary_t::container_type& init);
|
||||
static basic_json binary(typename binary_t::container_type&& init);
|
||||
|
||||
// (2)
|
||||
static basic_json binary(const typename binary_t::container_type& init,
|
||||
std::uint8_t subtype);
|
||||
static basic_json binary(typename binary_t::container_type&& init,
|
||||
std::uint8_t subtype);
|
||||
```
|
||||
|
||||
1. Creates a JSON binary array value from a given binary container.
|
||||
2. Creates a JSON binary array value from a given binary container with subtype.
|
||||
|
||||
Binary values are part of various binary formats, such as CBOR, MessagePack, and BSON. This constructor is used to
|
||||
create a value for serialization to those formats.
|
||||
|
||||
## Parameters
|
||||
|
||||
`init` (in)
|
||||
: container containing bytes to use as a binary type
|
||||
|
||||
`subtype` (in)
|
||||
: subtype to use in CBOR, MessagePack, and BSON
|
||||
|
||||
## Return value
|
||||
|
||||
JSON binary array value
|
||||
|
||||
## Exception safety
|
||||
|
||||
Strong guarantee: if an exception is thrown, there are no changes in the JSON value.
|
||||
|
||||
## Complexity
|
||||
|
||||
Linear in the size of `init`; constant for `typename binary_t::container_type&& init` versions.
|
||||
|
||||
## Notes
|
||||
|
||||
Note, this function exists because of the difficulty in correctly specifying the correct template overload in the
|
||||
standard value ctor, as both JSON arrays and JSON binary arrays are backed with some form of a `std::vector`. Because
|
||||
JSON binary arrays are a non-standard extension, it was decided that it would be best to prevent automatic
|
||||
initialization of a binary array type, for backwards compatibility and so it does not happen on accident.
|
||||
|
||||
## Examples
|
||||
|
||||
??? example
|
||||
|
||||
The following code shows how to create a binary value.
|
||||
|
||||
```cpp
|
||||
--8<-- "examples/binary.cpp"
|
||||
```
|
||||
|
||||
Output:
|
||||
|
||||
```json
|
||||
--8<-- "examples/binary.output"
|
||||
```
|
||||
|
||||
## Version history
|
||||
|
||||
- Added in version 3.8.0.
|
||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1,75 @@
|
||||
# nlohmann::basic_json::binary
|
||||
|
||||
```
|
||||
// (1)
|
||||
static basic_json binary(const typename binary_t::container_type& init);
|
||||
static basic_json binary(typename binary_t::container_type&& init);
|
||||
|
||||
// (2)
|
||||
static basic_json binary(const typename binary_t::container_type& init,
|
||||
std::uint8_t subtype);
|
||||
static basic_json binary(typename binary_t::container_type&& init,
|
||||
std::uint8_t subtype);
|
||||
```
|
||||
|
||||
1. Creates a JSON binary array value from a given binary container.
|
||||
1. Creates a JSON binary array value from a given binary container with subtype.
|
||||
|
||||
Binary values are part of various binary formats, such as CBOR, MessagePack, and BSON. This constructor is used to create a value for serialization to those formats.
|
||||
|
||||
## Parameters
|
||||
|
||||
`init` (in) : container containing bytes to use as a binary type
|
||||
|
||||
`subtype` (in) : subtype to use in CBOR, MessagePack, and BSON
|
||||
|
||||
## Return value
|
||||
|
||||
JSON binary array value
|
||||
|
||||
## Exception safety
|
||||
|
||||
Strong guarantee: if an exception is thrown, there are no changes in the JSON value.
|
||||
|
||||
## Complexity
|
||||
|
||||
Linear in the size of `init`; constant for `typename binary_t::container_type&& init` versions.
|
||||
|
||||
## Notes
|
||||
|
||||
Note, this function exists because of the difficulty in correctly specifying the correct template overload in the standard value ctor, as both JSON arrays and JSON binary arrays are backed with some form of a `std::vector`. Because JSON binary arrays are a non-standard extension, it was decided that it would be best to prevent automatic initialization of a binary array type, for backwards compatibility and so it does not happen on accident.
|
||||
|
||||
## Examples
|
||||
|
||||
Example
|
||||
|
||||
The following code shows how to create a binary value.
|
||||
|
||||
```
|
||||
#include <iostream>
|
||||
#include <nlohmann/json.hpp>
|
||||
|
||||
using json = nlohmann::json;
|
||||
|
||||
int main()
|
||||
{
|
||||
// create a binary vector
|
||||
std::vector<std::uint8_t> vec = {0xCA, 0xFE, 0xBA, 0xBE};
|
||||
|
||||
// create a binary JSON value with subtype 42
|
||||
json j = json::binary(vec, 42);
|
||||
|
||||
// output type and subtype
|
||||
std::cout << "type: " << j.type_name() << ", subtype: " << j.get_binary().subtype() << std::endl;
|
||||
}
|
||||
```
|
||||
|
||||
Output:
|
||||
|
||||
```
|
||||
type: binary, subtype: 42
|
||||
```
|
||||
|
||||
## Version history
|
||||
|
||||
- Added in version 3.8.0.
|
||||
@@ -0,0 +1,129 @@
|
||||
# <small>nlohmann::basic_json::</small>binary_t
|
||||
|
||||
```cpp
|
||||
using binary_t = byte_container_with_subtype<BinaryType>;
|
||||
```
|
||||
|
||||
This type is a type designed to carry binary data that appears in various serialized formats, such as CBOR's Major Type
|
||||
2, MessagePack's bin, and BSON's generic binary subtype. This type is NOT a part of standard JSON and exists solely for
|
||||
compatibility with these binary types. As such, it is simply defined as an ordered sequence of zero or more byte values.
|
||||
|
||||
Additionally, as an implementation detail, the subtype of the binary data is carried around as a `std::uint64_t`, which
|
||||
is compatible with both of the binary data formats that use binary subtyping, (though the specific numbering is
|
||||
incompatible with each other, and it is up to the user to translate between them). The subtype is added to `BinaryType`
|
||||
via the helper type [byte_container_with_subtype](../byte_container_with_subtype/index.md).
|
||||
|
||||
[CBOR's RFC 7049](https://tools.ietf.org/html/rfc7049) describes this type as:
|
||||
> Major type 2: a byte string. The string's length in bytes is represented following the rules for positive integers
|
||||
> (major type 0).
|
||||
|
||||
[MessagePack's documentation on the bin type
|
||||
family](https://github.com/msgpack/msgpack/blob/master/spec.md#bin-format-family) describes this type as:
|
||||
> Bin format family stores a byte array in 2, 3, or 5 bytes of extra bytes in addition to the size of the byte array.
|
||||
|
||||
[BSON's specifications](http://bsonspec.org/spec.html) describe several binary types; however, this type is intended to
|
||||
represent the generic binary type which has the description:
|
||||
> Generic binary subtype - This is the most commonly used binary subtype and should be the 'default' for drivers and
|
||||
> tools.
|
||||
|
||||
None of these impose any limitations on the internal representation other than the basic unit of storage be some type of
|
||||
array whose parts are decomposable into bytes.
|
||||
|
||||
The default representation of this binary format is a `#!cpp std::vector<std::uint8_t>`, which is a very common way to
|
||||
represent a byte array in modern C++.
|
||||
|
||||
## Template parameters
|
||||
|
||||
`BinaryType`
|
||||
: container type to store arrays
|
||||
|
||||
Although not formally expressed as a C++ concept, `BinaryType` must be default-constructible,
|
||||
copy/move-constructible, and support `push_back()`, `.data()`, and `.size()`, because
|
||||
[`byte_container_with_subtype`](../byte_container_with_subtype/index.md) derives directly from it. Its
|
||||
`value_type` must additionally be exactly one byte wide (e.g., `std::uint8_t`/`char`/`std::byte`): the binary
|
||||
serializers (CBOR, MessagePack, BSON, UBJSON) read and write the container's raw bytes via
|
||||
`reinterpret_cast`, which is only correct for byte-sized elements -- a container like
|
||||
`#!cpp std::vector<std::intptr_t>` will not work as `BinaryType`.
|
||||
|
||||
## Notes
|
||||
|
||||
#### Default type
|
||||
|
||||
The default values for `BinaryType` is `#!cpp std::vector<std::uint8_t>`.
|
||||
|
||||
#### Custom BinaryType behavior
|
||||
|
||||
When a custom `BinaryType` is configured (other than the default `#!cpp std::vector<std::uint8_t>`), you can assign
|
||||
values of that type directly to a `basic_json` instance, and they will automatically be recognized as binary values
|
||||
rather than arrays:
|
||||
|
||||
```cpp
|
||||
using custom_json = nlohmann::basic_json<
|
||||
nlohmann::ordered_map, // ObjectType
|
||||
std::vector, // ArrayType
|
||||
std::string, // StringType
|
||||
bool, // BooleanType
|
||||
std::int64_t, // NumberIntegerType
|
||||
std::uint64_t, // NumberUnsignedType
|
||||
double, // NumberFloatType
|
||||
std::allocator, // AllocatorType
|
||||
nlohmann::adl_serializer,
|
||||
std::vector<std::byte> // Custom BinaryType
|
||||
>;
|
||||
|
||||
std::vector<std::byte> data{std::byte{1}, std::byte{2}, std::byte{3}};
|
||||
custom_json j = data; // Creates a binary value, not an array
|
||||
assert(j.is_binary());
|
||||
|
||||
// Round-tripping works seamlessly
|
||||
auto extracted = j.get<std::vector<std::byte>>();
|
||||
assert(extracted == data);
|
||||
```
|
||||
|
||||
This automatic type detection is a convenience feature that only applies to custom (non-default) `BinaryType` configurations.
|
||||
The default `nlohmann::json` continues to treat `#!cpp std::vector<std::uint8_t>` as arrays for backward compatibility.
|
||||
|
||||
#### Storage
|
||||
|
||||
Binary Arrays are stored as pointers in a `basic_json` type. That is, for any access to array values, a pointer of the
|
||||
type `#!cpp binary_t*` must be dereferenced.
|
||||
|
||||
#### Notes on subtypes
|
||||
|
||||
- CBOR
|
||||
- Binary values are represented as byte strings. Subtypes are written as tags.
|
||||
|
||||
- MessagePack
|
||||
- If a subtype is given and the binary array contains exactly 1, 2, 4, 8, or 16 elements, the fixext family (fixext1,
|
||||
fixext2, fixext4, fixext8) is used. For other sizes, the ext family (ext8, ext16, ext32) is used. The subtype is
|
||||
then added as a signed 8-bit integer.
|
||||
- If no subtype is given, the bin family (bin8, bin16, bin32) is used.
|
||||
|
||||
- BSON
|
||||
- If a subtype is given, it is used and added as an unsigned 8-bit integer.
|
||||
- If no subtype is given, the generic binary subtype 0x00 is used.
|
||||
|
||||
## Examples
|
||||
|
||||
??? example
|
||||
|
||||
The following code shows that `binary_t` is by default, a typedef to
|
||||
`#!cpp nlohmann::byte_container_with_subtype<std::vector<std::uint8_t>>`.
|
||||
|
||||
```cpp
|
||||
--8<-- "examples/binary_t.cpp"
|
||||
```
|
||||
|
||||
Output:
|
||||
|
||||
```json
|
||||
--8<-- "examples/binary_t.output"
|
||||
```
|
||||
|
||||
## See also
|
||||
|
||||
- [byte_container_with_subtype](../byte_container_with_subtype/index.md)
|
||||
|
||||
## Version history
|
||||
|
||||
- Added in version 3.8.0. Changed the type of subtype to `std::uint64_t` in version 3.10.0.
|
||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1,127 @@
|
||||
# nlohmann::basic_json::binary_t
|
||||
|
||||
```
|
||||
using binary_t = byte_container_with_subtype<BinaryType>;
|
||||
```
|
||||
|
||||
This type is a type designed to carry binary data that appears in various serialized formats, such as CBOR's Major Type 2, MessagePack's bin, and BSON's generic binary subtype. This type is NOT a part of standard JSON and exists solely for compatibility with these binary types. As such, it is simply defined as an ordered sequence of zero or more byte values.
|
||||
|
||||
Additionally, as an implementation detail, the subtype of the binary data is carried around as a `std::uint64_t`, which is compatible with both of the binary data formats that use binary subtyping, (though the specific numbering is incompatible with each other, and it is up to the user to translate between them). The subtype is added to `BinaryType` via the helper type [byte_container_with_subtype](https://json.nlohmann.me/api/byte_container_with_subtype/index.md).
|
||||
|
||||
[CBOR's RFC 7049](https://tools.ietf.org/html/rfc7049) describes this type as:
|
||||
|
||||
> Major type 2: a byte string. The string's length in bytes is represented following the rules for positive integers (major type 0).
|
||||
|
||||
[MessagePack's documentation on the bin type family](https://github.com/msgpack/msgpack/blob/master/spec.md#bin-format-family) describes this type as:
|
||||
|
||||
> Bin format family stores a byte array in 2, 3, or 5 bytes of extra bytes in addition to the size of the byte array.
|
||||
|
||||
[BSON's specifications](http://bsonspec.org/spec.html) describe several binary types; however, this type is intended to represent the generic binary type which has the description:
|
||||
|
||||
> Generic binary subtype - This is the most commonly used binary subtype and should be the 'default' for drivers and tools.
|
||||
|
||||
None of these impose any limitations on the internal representation other than the basic unit of storage be some type of array whose parts are decomposable into bytes.
|
||||
|
||||
The default representation of this binary format is a `std::vector<std::uint8_t>`, which is a very common way to represent a byte array in modern C++.
|
||||
|
||||
## Template parameters
|
||||
|
||||
`BinaryType` : container type to store arrays
|
||||
|
||||
```
|
||||
Although not formally expressed as a C++ concept, `BinaryType` must be default-constructible,
|
||||
copy/move-constructible, and support `push_back()`, `.data()`, and `.size()`, because
|
||||
[`byte_container_with_subtype`](https://json.nlohmann.me/api/byte_container_with_subtype/index.md) derives directly from it. Its
|
||||
`value_type` must additionally be exactly one byte wide (e.g., `std::uint8_t`/`char`/`std::byte`): the binary
|
||||
serializers (CBOR, MessagePack, BSON, UBJSON) read and write the container's raw bytes via
|
||||
`reinterpret_cast`, which is only correct for byte-sized elements -- a container like
|
||||
`std::vector<std::intptr_t>` will not work as `BinaryType`.
|
||||
```
|
||||
|
||||
## Notes
|
||||
|
||||
#### Default type
|
||||
|
||||
The default values for `BinaryType` is `std::vector<std::uint8_t>`.
|
||||
|
||||
#### Custom BinaryType behavior
|
||||
|
||||
When a custom `BinaryType` is configured (other than the default `std::vector<std::uint8_t>`), you can assign values of that type directly to a `basic_json` instance, and they will automatically be recognized as binary values rather than arrays:
|
||||
|
||||
```
|
||||
using custom_json = nlohmann::basic_json<
|
||||
nlohmann::ordered_map, // ObjectType
|
||||
std::vector, // ArrayType
|
||||
std::string, // StringType
|
||||
bool, // BooleanType
|
||||
std::int64_t, // NumberIntegerType
|
||||
std::uint64_t, // NumberUnsignedType
|
||||
double, // NumberFloatType
|
||||
std::allocator, // AllocatorType
|
||||
nlohmann::adl_serializer,
|
||||
std::vector<std::byte> // Custom BinaryType
|
||||
>;
|
||||
|
||||
std::vector<std::byte> data{std::byte{1}, std::byte{2}, std::byte{3}};
|
||||
custom_json j = data; // Creates a binary value, not an array
|
||||
assert(j.is_binary());
|
||||
|
||||
// Round-tripping works seamlessly
|
||||
auto extracted = j.get<std::vector<std::byte>>();
|
||||
assert(extracted == data);
|
||||
```
|
||||
|
||||
This automatic type detection is a convenience feature that only applies to custom (non-default) `BinaryType` configurations. The default `nlohmann::json` continues to treat `std::vector<std::uint8_t>` as arrays for backward compatibility.
|
||||
|
||||
#### Storage
|
||||
|
||||
Binary Arrays are stored as pointers in a `basic_json` type. That is, for any access to array values, a pointer of the type `binary_t*` must be dereferenced.
|
||||
|
||||
#### Notes on subtypes
|
||||
|
||||
- CBOR
|
||||
|
||||
- Binary values are represented as byte strings. Subtypes are written as tags.
|
||||
|
||||
- MessagePack
|
||||
|
||||
- If a subtype is given and the binary array contains exactly 1, 2, 4, 8, or 16 elements, the fixext family (fixext1, fixext2, fixext4, fixext8) is used. For other sizes, the ext family (ext8, ext16, ext32) is used. The subtype is then added as a signed 8-bit integer.
|
||||
- If no subtype is given, the bin family (bin8, bin16, bin32) is used.
|
||||
|
||||
- BSON
|
||||
|
||||
- If a subtype is given, it is used and added as an unsigned 8-bit integer.
|
||||
- If no subtype is given, the generic binary subtype 0x00 is used.
|
||||
|
||||
## Examples
|
||||
|
||||
Example
|
||||
|
||||
The following code shows that `binary_t` is by default, a typedef to `nlohmann::byte_container_with_subtype<std::vector<std::uint8_t>>`.
|
||||
|
||||
```
|
||||
#include <iostream>
|
||||
#include <iomanip>
|
||||
#include <nlohmann/json.hpp>
|
||||
|
||||
using json = nlohmann::json;
|
||||
|
||||
int main()
|
||||
{
|
||||
std::cout << std::boolalpha << std::is_same<nlohmann::byte_container_with_subtype<std::vector<std::uint8_t>>, json::binary_t>::value << std::endl;
|
||||
}
|
||||
```
|
||||
|
||||
Output:
|
||||
|
||||
```
|
||||
true
|
||||
```
|
||||
|
||||
## See also
|
||||
|
||||
- [byte_container_with_subtype](https://json.nlohmann.me/api/byte_container_with_subtype/index.md)
|
||||
|
||||
## Version history
|
||||
|
||||
- Added in version 3.8.0. Changed the type of subtype to `std::uint64_t` in version 3.10.0.
|
||||
@@ -0,0 +1,42 @@
|
||||
# <small>nlohmann::basic_json::</small>boolean_t
|
||||
|
||||
```cpp
|
||||
using boolean_t = BooleanType;
|
||||
```
|
||||
|
||||
The type used to store JSON booleans.
|
||||
|
||||
[RFC 8259](https://tools.ietf.org/html/rfc8259) implicitly describes a boolean as a type which differentiates the two
|
||||
literals `#!json true` and `#!json false`.
|
||||
|
||||
To store boolean values in C++, a type is defined by the template parameter `BooleanType` which chooses the type to use.
|
||||
|
||||
## Notes
|
||||
|
||||
#### Default type
|
||||
|
||||
With the default values for `BooleanType` (`#!cpp bool`), the default value for `boolean_t` is `#!cpp bool`.
|
||||
|
||||
#### Storage
|
||||
|
||||
Boolean values are stored directly inside a `basic_json` type.
|
||||
|
||||
## Examples
|
||||
|
||||
??? example
|
||||
|
||||
The following code shows that `boolean_t` is by default, a typedef to `#!cpp bool`.
|
||||
|
||||
```cpp
|
||||
--8<-- "examples/boolean_t.cpp"
|
||||
```
|
||||
|
||||
Output:
|
||||
|
||||
```json
|
||||
--8<-- "examples/boolean_t.output"
|
||||
```
|
||||
|
||||
## Version history
|
||||
|
||||
- Added in version 1.0.0.
|
||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1,50 @@
|
||||
# nlohmann::basic_json::boolean_t
|
||||
|
||||
```
|
||||
using boolean_t = BooleanType;
|
||||
```
|
||||
|
||||
The type used to store JSON booleans.
|
||||
|
||||
[RFC 8259](https://tools.ietf.org/html/rfc8259) implicitly describes a boolean as a type which differentiates the two literals `true` and `false`.
|
||||
|
||||
To store boolean values in C++, a type is defined by the template parameter `BooleanType` which chooses the type to use.
|
||||
|
||||
## Notes
|
||||
|
||||
#### Default type
|
||||
|
||||
With the default values for `BooleanType` (`bool`), the default value for `boolean_t` is `bool`.
|
||||
|
||||
#### Storage
|
||||
|
||||
Boolean values are stored directly inside a `basic_json` type.
|
||||
|
||||
## Examples
|
||||
|
||||
Example
|
||||
|
||||
The following code shows that `boolean_t` is by default, a typedef to `bool`.
|
||||
|
||||
```
|
||||
#include <iostream>
|
||||
#include <iomanip>
|
||||
#include <nlohmann/json.hpp>
|
||||
|
||||
using json = nlohmann::json;
|
||||
|
||||
int main()
|
||||
{
|
||||
std::cout << std::boolalpha << std::is_same<bool, json::boolean_t>::value << std::endl;
|
||||
}
|
||||
```
|
||||
|
||||
Output:
|
||||
|
||||
```
|
||||
true
|
||||
```
|
||||
|
||||
## Version history
|
||||
|
||||
- Added in version 1.0.0.
|
||||
@@ -0,0 +1,41 @@
|
||||
# <small>nlohmann::basic_json::</small>cbegin
|
||||
|
||||
```cpp
|
||||
const_iterator cbegin() const noexcept;
|
||||
```
|
||||
|
||||
Returns an iterator to the first element.
|
||||
|
||||

|
||||
|
||||
## Return value
|
||||
|
||||
iterator to the first element
|
||||
|
||||
## Exception safety
|
||||
|
||||
No-throw guarantee: this member function never throws exceptions.
|
||||
|
||||
## Complexity
|
||||
|
||||
Constant.
|
||||
|
||||
## Examples
|
||||
|
||||
??? example
|
||||
|
||||
The following code shows an example for `cbegin()`.
|
||||
|
||||
```cpp
|
||||
--8<-- "examples/cbegin.cpp"
|
||||
```
|
||||
|
||||
Output:
|
||||
|
||||
```json
|
||||
--8<-- "examples/cbegin.output"
|
||||
```
|
||||
|
||||
## Version history
|
||||
|
||||
- Added in version 1.0.0.
|
||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1,54 @@
|
||||
# nlohmann::basic_json::cbegin
|
||||
|
||||
```
|
||||
const_iterator cbegin() const noexcept;
|
||||
```
|
||||
|
||||
Returns an iterator to the first element.
|
||||
|
||||
## Return value
|
||||
|
||||
iterator to the first element
|
||||
|
||||
## Exception safety
|
||||
|
||||
No-throw guarantee: this member function never throws exceptions.
|
||||
|
||||
## Complexity
|
||||
|
||||
Constant.
|
||||
|
||||
## Examples
|
||||
|
||||
Example
|
||||
|
||||
The following code shows an example for `cbegin()`.
|
||||
|
||||
```
|
||||
#include <iostream>
|
||||
#include <nlohmann/json.hpp>
|
||||
|
||||
using json = nlohmann::json;
|
||||
|
||||
int main()
|
||||
{
|
||||
// create an array value
|
||||
const json array = {1, 2, 3, 4, 5};
|
||||
|
||||
// get an iterator to the first element
|
||||
json::const_iterator it = array.cbegin();
|
||||
|
||||
// serialize the element that the iterator points to
|
||||
std::cout << *it << '\n';
|
||||
}
|
||||
```
|
||||
|
||||
Output:
|
||||
|
||||
```
|
||||
1
|
||||
```
|
||||
|
||||
## Version history
|
||||
|
||||
- Added in version 1.0.0.
|
||||
@@ -0,0 +1,42 @@
|
||||
# <small>nlohmann::basic_json::</small>cbor_tag_handler_t
|
||||
|
||||
```cpp
|
||||
enum class cbor_tag_handler_t
|
||||
{
|
||||
error,
|
||||
ignore,
|
||||
store
|
||||
};
|
||||
```
|
||||
|
||||
This enumeration is used in the [`from_cbor`](from_cbor.md) function to choose how to treat tags:
|
||||
|
||||
error
|
||||
: throw a `parse_error` exception in case of a tag
|
||||
|
||||
ignore
|
||||
: ignore tags
|
||||
|
||||
store
|
||||
: store tagged values as binary container with subtype (for bytes 0xd8..0xdb)
|
||||
|
||||
## Examples
|
||||
|
||||
??? example
|
||||
|
||||
The example below shows how the different values of the `cbor_tag_handler_t` influence the behavior of
|
||||
[`from_cbor`](from_cbor.md) when reading a tagged byte string.
|
||||
|
||||
```cpp
|
||||
--8<-- "examples/cbor_tag_handler_t.cpp"
|
||||
```
|
||||
|
||||
Output:
|
||||
|
||||
```json
|
||||
--8<-- "examples/cbor_tag_handler_t.output"
|
||||
```
|
||||
|
||||
## Version history
|
||||
|
||||
- Added in version 3.9.0. Added value `store` in 3.10.0.
|
||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1,67 @@
|
||||
# nlohmann::basic_json::cbor_tag_handler_t
|
||||
|
||||
```
|
||||
enum class cbor_tag_handler_t
|
||||
{
|
||||
error,
|
||||
ignore,
|
||||
store
|
||||
};
|
||||
```
|
||||
|
||||
This enumeration is used in the [`from_cbor`](https://json.nlohmann.me/api/basic_json/from_cbor/index.md) function to choose how to treat tags:
|
||||
|
||||
error : throw a `parse_error` exception in case of a tag
|
||||
|
||||
ignore : ignore tags
|
||||
|
||||
store : store tagged values as binary container with subtype (for bytes 0xd8..0xdb)
|
||||
|
||||
## Examples
|
||||
|
||||
Example
|
||||
|
||||
The example below shows how the different values of the `cbor_tag_handler_t` influence the behavior of [`from_cbor`](https://json.nlohmann.me/api/basic_json/from_cbor/index.md) when reading a tagged byte string.
|
||||
|
||||
```
|
||||
#include <iostream>
|
||||
#include <nlohmann/json.hpp>
|
||||
|
||||
using json = nlohmann::json;
|
||||
|
||||
int main()
|
||||
{
|
||||
// tagged byte string
|
||||
std::vector<std::uint8_t> vec = {{0xd8, 0x42, 0x44, 0xcA, 0xfe, 0xba, 0xbe}};
|
||||
|
||||
// cbor_tag_handler_t::error throws
|
||||
try
|
||||
{
|
||||
auto b_throw_on_tag = json::from_cbor(vec, true, true, json::cbor_tag_handler_t::error);
|
||||
}
|
||||
catch (const json::parse_error& e)
|
||||
{
|
||||
std::cout << e.what() << std::endl;
|
||||
}
|
||||
|
||||
// cbor_tag_handler_t::ignore ignores the tag
|
||||
auto b_ignore_tag = json::from_cbor(vec, true, true, json::cbor_tag_handler_t::ignore);
|
||||
std::cout << b_ignore_tag << std::endl;
|
||||
|
||||
// cbor_tag_handler_t::store stores the tag as binary subtype
|
||||
auto b_store_tag = json::from_cbor(vec, true, true, json::cbor_tag_handler_t::store);
|
||||
std::cout << b_store_tag << std::endl;
|
||||
}
|
||||
```
|
||||
|
||||
Output:
|
||||
|
||||
```
|
||||
[json.exception.parse_error.112] parse error at byte 1: syntax error while parsing CBOR value: invalid byte: 0xD8
|
||||
{"bytes":[202,254,186,190],"subtype":null}
|
||||
{"bytes":[202,254,186,190],"subtype":66}
|
||||
```
|
||||
|
||||
## Version history
|
||||
|
||||
- Added in version 3.9.0. Added value `store` in 3.10.0.
|
||||
@@ -0,0 +1,41 @@
|
||||
# <small>nlohmann::basic_json::</small>cend
|
||||
|
||||
```cpp
|
||||
const_iterator cend() const noexcept;
|
||||
```
|
||||
|
||||
Returns an iterator to one past the last element.
|
||||
|
||||

|
||||
|
||||
## Return value
|
||||
|
||||
iterator one past the last element
|
||||
|
||||
## Exception safety
|
||||
|
||||
No-throw guarantee: this member function never throws exceptions.
|
||||
|
||||
## Complexity
|
||||
|
||||
Constant.
|
||||
|
||||
## Examples
|
||||
|
||||
??? example
|
||||
|
||||
The following code shows an example for `cend()`.
|
||||
|
||||
```cpp
|
||||
--8<-- "examples/cend.cpp"
|
||||
```
|
||||
|
||||
Output:
|
||||
|
||||
```json
|
||||
--8<-- "examples/cend.output"
|
||||
```
|
||||
|
||||
## Version history
|
||||
|
||||
- Added in version 1.0.0.
|
||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1,57 @@
|
||||
# nlohmann::basic_json::cend
|
||||
|
||||
```
|
||||
const_iterator cend() const noexcept;
|
||||
```
|
||||
|
||||
Returns an iterator to one past the last element.
|
||||
|
||||
## Return value
|
||||
|
||||
iterator one past the last element
|
||||
|
||||
## Exception safety
|
||||
|
||||
No-throw guarantee: this member function never throws exceptions.
|
||||
|
||||
## Complexity
|
||||
|
||||
Constant.
|
||||
|
||||
## Examples
|
||||
|
||||
Example
|
||||
|
||||
The following code shows an example for `cend()`.
|
||||
|
||||
```
|
||||
#include <iostream>
|
||||
#include <nlohmann/json.hpp>
|
||||
|
||||
using json = nlohmann::json;
|
||||
|
||||
int main()
|
||||
{
|
||||
// create an array value
|
||||
json array = {1, 2, 3, 4, 5};
|
||||
|
||||
// get an iterator to one past the last element
|
||||
json::const_iterator it = array.cend();
|
||||
|
||||
// decrement the iterator to point to the last element
|
||||
--it;
|
||||
|
||||
// serialize the element that the iterator points to
|
||||
std::cout << *it << '\n';
|
||||
}
|
||||
```
|
||||
|
||||
Output:
|
||||
|
||||
```
|
||||
5
|
||||
```
|
||||
|
||||
## Version history
|
||||
|
||||
- Added in version 1.0.0.
|
||||
@@ -0,0 +1,58 @@
|
||||
# <small>nlohmann::basic_json::</small>clear
|
||||
|
||||
```cpp
|
||||
void clear() noexcept;
|
||||
```
|
||||
|
||||
Clears the content of a JSON value and resets it to the default value as if [`basic_json(value_t)`](basic_json.md) would
|
||||
have been called with the current value type from [`type()`](type.md):
|
||||
|
||||
| Value type | initial value |
|
||||
|------------|----------------------|
|
||||
| null | `null` |
|
||||
| boolean | `false` |
|
||||
| string | `""` |
|
||||
| number | `0` |
|
||||
| binary | An empty byte vector |
|
||||
| object | `{}` |
|
||||
| array | `[]` |
|
||||
|
||||
Has the same effect as calling
|
||||
|
||||
```.cpp
|
||||
*this = basic_json(type());
|
||||
```
|
||||
|
||||
## Exception safety
|
||||
|
||||
No-throw guarantee: this function never throws exceptions.
|
||||
|
||||
## Complexity
|
||||
|
||||
Linear in the size of the JSON value.
|
||||
|
||||
## Notes
|
||||
|
||||
All iterators, pointers, and references related to this container are invalidated.
|
||||
|
||||
## Examples
|
||||
|
||||
??? example
|
||||
|
||||
The example below shows the effect of `clear()` to different
|
||||
JSON types.
|
||||
|
||||
```cpp
|
||||
--8<-- "examples/clear.cpp"
|
||||
```
|
||||
|
||||
Output:
|
||||
|
||||
```json
|
||||
--8<-- "examples/clear.output"
|
||||
```
|
||||
|
||||
## Version history
|
||||
|
||||
- Added in version 1.0.0.
|
||||
- Added support for binary types in version 3.8.0.
|
||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1,95 @@
|
||||
# nlohmann::basic_json::clear
|
||||
|
||||
```
|
||||
void clear() noexcept;
|
||||
```
|
||||
|
||||
Clears the content of a JSON value and resets it to the default value as if [`basic_json(value_t)`](https://json.nlohmann.me/api/basic_json/basic_json/index.md) would have been called with the current value type from [`type()`](https://json.nlohmann.me/api/basic_json/type/index.md):
|
||||
|
||||
| Value type | initial value |
|
||||
| ---------- | -------------------- |
|
||||
| null | `null` |
|
||||
| boolean | `false` |
|
||||
| string | `""` |
|
||||
| number | `0` |
|
||||
| binary | An empty byte vector |
|
||||
| object | `{}` |
|
||||
| array | `[]` |
|
||||
|
||||
Has the same effect as calling
|
||||
|
||||
```
|
||||
*this = basic_json(type());
|
||||
```
|
||||
|
||||
## Exception safety
|
||||
|
||||
No-throw guarantee: this function never throws exceptions.
|
||||
|
||||
## Complexity
|
||||
|
||||
Linear in the size of the JSON value.
|
||||
|
||||
## Notes
|
||||
|
||||
All iterators, pointers, and references related to this container are invalidated.
|
||||
|
||||
## Examples
|
||||
|
||||
Example
|
||||
|
||||
The example below shows the effect of `clear()` to different JSON types.
|
||||
|
||||
```
|
||||
#include <iostream>
|
||||
#include <nlohmann/json.hpp>
|
||||
|
||||
using json = nlohmann::json;
|
||||
|
||||
int main()
|
||||
{
|
||||
// create JSON values
|
||||
json j_null;
|
||||
json j_boolean = true;
|
||||
json j_number_integer = 17;
|
||||
json j_number_float = 23.42;
|
||||
json j_object = {{"one", 1}, {"two", 2}};
|
||||
json j_array = {1, 2, 4, 8, 16};
|
||||
json j_string = "Hello, world";
|
||||
|
||||
// call clear()
|
||||
j_null.clear();
|
||||
j_boolean.clear();
|
||||
j_number_integer.clear();
|
||||
j_number_float.clear();
|
||||
j_object.clear();
|
||||
j_array.clear();
|
||||
j_string.clear();
|
||||
|
||||
// serialize the cleared values()
|
||||
std::cout << j_null << '\n';
|
||||
std::cout << j_boolean << '\n';
|
||||
std::cout << j_number_integer << '\n';
|
||||
std::cout << j_number_float << '\n';
|
||||
std::cout << j_object << '\n';
|
||||
std::cout << j_array << '\n';
|
||||
std::cout << j_string << '\n';
|
||||
}
|
||||
```
|
||||
|
||||
Output:
|
||||
|
||||
```
|
||||
null
|
||||
false
|
||||
0
|
||||
0.0
|
||||
{}
|
||||
[]
|
||||
""
|
||||
```
|
||||
|
||||
## Version history
|
||||
|
||||
- Added in version 1.0.0.
|
||||
- Added support for binary types in version 3.8.0.
|
||||
@@ -0,0 +1,119 @@
|
||||
# <small>nlohmann::basic_json::</small>contains
|
||||
|
||||
```cpp
|
||||
// (1)
|
||||
bool contains(const typename object_t::key_type& key) const;
|
||||
|
||||
// (2)
|
||||
template<typename KeyType>
|
||||
bool contains(KeyType&& key) const;
|
||||
|
||||
// (3)
|
||||
bool contains(const json_pointer& ptr) const;
|
||||
```
|
||||
|
||||
1. Check whether an element exists in a JSON object with a key equivalent to `key`. If the element is not found or the
|
||||
JSON value is not an object, `#!cpp false` is returned.
|
||||
2. See 1. This overload is only available if `KeyType` is comparable with `#!cpp typename object_t::key_type` and
|
||||
`#!cpp typename object_comparator_t::is_transparent` denotes a type.
|
||||
3. Check whether the given JSON pointer `ptr` can be resolved in the current JSON value.
|
||||
|
||||
## Template parameters
|
||||
|
||||
`KeyType`
|
||||
: A type for an object key other than [`json_pointer`](../json_pointer/index.md) that is comparable with
|
||||
[`string_t`](string_t.md) using [`object_comparator_t`](object_comparator_t.md).
|
||||
This can also be a string view (C++17).
|
||||
|
||||
## Parameters
|
||||
|
||||
`key` (in)
|
||||
: key value to check its existence.
|
||||
|
||||
`ptr` (in)
|
||||
: JSON pointer to check its existence.
|
||||
|
||||
## Return value
|
||||
|
||||
1. `#!cpp true` if an element with specified `key` exists. If no such element with such a key is found or the JSON value
|
||||
is not an object, `#!cpp false` is returned.
|
||||
2. See 1.
|
||||
3. `#!cpp true` if the JSON pointer can be resolved to a stored value, `#!cpp false` otherwise.
|
||||
|
||||
## Exception safety
|
||||
|
||||
Strong exception safety: if an exception occurs, the original value stays intact.
|
||||
|
||||
## Exceptions
|
||||
|
||||
1. The function does not throw exceptions.
|
||||
2. The function does not throw exceptions.
|
||||
3. The function does not throw exceptions.
|
||||
|
||||
## Complexity
|
||||
|
||||
Logarithmic in the size of the JSON object.
|
||||
|
||||
## Notes
|
||||
|
||||
- This method always returns `#!cpp false` when executed on a JSON type that is not an object.
|
||||
- This method can be executed on any JSON value type.
|
||||
|
||||
!!! info "Postconditions"
|
||||
|
||||
If `#!cpp j.contains(x)` returns `#!c true` for a key or JSON pointer `x`, then it is safe to call `j[x]`.
|
||||
|
||||
## Examples
|
||||
|
||||
??? example "Example: (1) check with key"
|
||||
|
||||
The example shows how `contains()` is used.
|
||||
|
||||
```cpp
|
||||
--8<-- "examples/contains__object_t_key_type.cpp"
|
||||
```
|
||||
|
||||
Output:
|
||||
|
||||
```json
|
||||
--8<-- "examples/contains__object_t_key_type.output"
|
||||
```
|
||||
|
||||
??? example "Example: (2) check with key using string_view"
|
||||
|
||||
The example shows how `contains()` is used.
|
||||
|
||||
```cpp
|
||||
--8<-- "examples/contains__keytype.c++17.cpp"
|
||||
```
|
||||
|
||||
Output:
|
||||
|
||||
```json
|
||||
--8<-- "examples/contains__keytype.c++17.output"
|
||||
```
|
||||
|
||||
??? example "Example: (3) check with JSON pointer"
|
||||
|
||||
The example shows how `contains()` is used.
|
||||
|
||||
```cpp
|
||||
--8<-- "examples/contains__json_pointer.cpp"
|
||||
```
|
||||
|
||||
Output:
|
||||
|
||||
```json
|
||||
--8<-- "examples/contains__json_pointer.output"
|
||||
```
|
||||
|
||||
## See also
|
||||
|
||||
- [find](find.md) find a value in an object
|
||||
- [count](count.md) returns the number of occurrences of a key
|
||||
|
||||
## Version history
|
||||
|
||||
1. Added in version 3.11.0.
|
||||
2. Added in version 3.6.0. Extended template `KeyType` to support comparable types in version 3.11.0.
|
||||
3. Added in version 3.7.0.
|
||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1,199 @@
|
||||
# nlohmann::basic_json::contains
|
||||
|
||||
```
|
||||
// (1)
|
||||
bool contains(const typename object_t::key_type& key) const;
|
||||
|
||||
// (2)
|
||||
template<typename KeyType>
|
||||
bool contains(KeyType&& key) const;
|
||||
|
||||
// (3)
|
||||
bool contains(const json_pointer& ptr) const;
|
||||
```
|
||||
|
||||
1. Check whether an element exists in a JSON object with a key equivalent to `key`. If the element is not found or the JSON value is not an object, `false` is returned.
|
||||
1. See 1. This overload is only available if `KeyType` is comparable with `typename object_t::key_type` and `typename object_comparator_t::is_transparent` denotes a type.
|
||||
1. Check whether the given JSON pointer `ptr` can be resolved in the current JSON value.
|
||||
|
||||
## Template parameters
|
||||
|
||||
`KeyType` : A type for an object key other than [`json_pointer`](https://json.nlohmann.me/api/json_pointer/index.md) that is comparable with [`string_t`](https://json.nlohmann.me/api/basic_json/string_t/index.md) using [`object_comparator_t`](https://json.nlohmann.me/api/basic_json/object_comparator_t/index.md). This can also be a string view (C++17).
|
||||
|
||||
## Parameters
|
||||
|
||||
`key` (in) : key value to check its existence.
|
||||
|
||||
`ptr` (in) : JSON pointer to check its existence.
|
||||
|
||||
## Return value
|
||||
|
||||
1. `true` if an element with specified `key` exists. If no such element with such a key is found or the JSON value is not an object, `false` is returned.
|
||||
1. See 1.
|
||||
1. `true` if the JSON pointer can be resolved to a stored value, `false` otherwise.
|
||||
|
||||
## Exception safety
|
||||
|
||||
Strong exception safety: if an exception occurs, the original value stays intact.
|
||||
|
||||
## Exceptions
|
||||
|
||||
1. The function does not throw exceptions.
|
||||
1. The function does not throw exceptions.
|
||||
1. The function does not throw exceptions.
|
||||
|
||||
## Complexity
|
||||
|
||||
Logarithmic in the size of the JSON object.
|
||||
|
||||
## Notes
|
||||
|
||||
- This method always returns `false` when executed on a JSON type that is not an object.
|
||||
- This method can be executed on any JSON value type.
|
||||
|
||||
Postconditions
|
||||
|
||||
If `j.contains(x)` returns `true` for a key or JSON pointer `x`, then it is safe to call `j[x]`.
|
||||
|
||||
## Examples
|
||||
|
||||
Example: (1) check with key
|
||||
|
||||
The example shows how `contains()` is used.
|
||||
|
||||
```
|
||||
#include <iostream>
|
||||
#include <nlohmann/json.hpp>
|
||||
|
||||
using json = nlohmann::json;
|
||||
using namespace nlohmann::literals;
|
||||
|
||||
int main()
|
||||
{
|
||||
// create some JSON values
|
||||
json j_object = R"( {"key": "value"} )"_json;
|
||||
json j_array = R"( [1, 2, 3] )"_json;
|
||||
|
||||
// call contains
|
||||
std::cout << std::boolalpha <<
|
||||
"j_object contains 'key': " << j_object.contains("key") << '\n' <<
|
||||
"j_object contains 'another': " << j_object.contains("another") << '\n' <<
|
||||
"j_array contains 'key': " << j_array.contains("key") << std::endl;
|
||||
}
|
||||
```
|
||||
|
||||
Output:
|
||||
|
||||
```
|
||||
j_object contains 'key': true
|
||||
j_object contains 'another': false
|
||||
j_array contains 'key': false
|
||||
```
|
||||
|
||||
Example: (2) check with key using string_view
|
||||
|
||||
The example shows how `contains()` is used.
|
||||
|
||||
```
|
||||
#include <iostream>
|
||||
#include <string_view>
|
||||
#include <nlohmann/json.hpp>
|
||||
|
||||
using namespace std::string_view_literals;
|
||||
using json = nlohmann::json;
|
||||
using namespace nlohmann::literals;
|
||||
|
||||
int main()
|
||||
{
|
||||
// create some JSON values
|
||||
json j_object = R"( {"key": "value"} )"_json;
|
||||
json j_array = R"( [1, 2, 3] )"_json;
|
||||
|
||||
// call contains
|
||||
std::cout << std::boolalpha <<
|
||||
"j_object contains 'key': " << j_object.contains("key"sv) << '\n' <<
|
||||
"j_object contains 'another': " << j_object.contains("another"sv) << '\n' <<
|
||||
"j_array contains 'key': " << j_array.contains("key"sv) << std::endl;
|
||||
}
|
||||
```
|
||||
|
||||
Output:
|
||||
|
||||
```
|
||||
j_object contains 'key': true
|
||||
j_object contains 'another': false
|
||||
j_array contains 'key': false
|
||||
```
|
||||
|
||||
Example: (3) check with JSON pointer
|
||||
|
||||
The example shows how `contains()` is used.
|
||||
|
||||
```
|
||||
#include <iostream>
|
||||
#include <nlohmann/json.hpp>
|
||||
|
||||
using json = nlohmann::json;
|
||||
using namespace nlohmann::literals;
|
||||
|
||||
int main()
|
||||
{
|
||||
// create a JSON value
|
||||
json j =
|
||||
{
|
||||
{"number", 1}, {"string", "foo"}, {"array", {1, 2}}
|
||||
};
|
||||
|
||||
std::cout << std::boolalpha
|
||||
<< j.contains("/number"_json_pointer) << '\n'
|
||||
<< j.contains("/string"_json_pointer) << '\n'
|
||||
<< j.contains("/array"_json_pointer) << '\n'
|
||||
<< j.contains("/array/1"_json_pointer) << '\n'
|
||||
<< j.contains("/array/-"_json_pointer) << '\n'
|
||||
<< j.contains("/array/4"_json_pointer) << '\n'
|
||||
<< j.contains("/baz"_json_pointer) << std::endl;
|
||||
|
||||
try
|
||||
{
|
||||
// try to use an array index with leading '0'
|
||||
j.contains("/array/01"_json_pointer);
|
||||
}
|
||||
catch (const json::parse_error& e)
|
||||
{
|
||||
std::cout << e.what() << '\n';
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
// try to use an array index that is not a number
|
||||
j.contains("/array/one"_json_pointer);
|
||||
}
|
||||
catch (const json::parse_error& e)
|
||||
{
|
||||
std::cout << e.what() << '\n';
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Output:
|
||||
|
||||
```
|
||||
true
|
||||
true
|
||||
true
|
||||
true
|
||||
false
|
||||
false
|
||||
false
|
||||
```
|
||||
|
||||
## See also
|
||||
|
||||
- [find](https://json.nlohmann.me/api/basic_json/find/index.md) find a value in an object
|
||||
- [count](https://json.nlohmann.me/api/basic_json/count/index.md) returns the number of occurrences of a key
|
||||
|
||||
## Version history
|
||||
|
||||
1. Added in version 3.11.0.
|
||||
1. Added in version 3.6.0. Extended template `KeyType` to support comparable types in version 3.11.0.
|
||||
1. Added in version 3.7.0.
|
||||
@@ -0,0 +1,83 @@
|
||||
# <small>nlohmann::basic_json::</small>count
|
||||
|
||||
```cpp
|
||||
// (1)
|
||||
size_type count(const typename object_t::key_type& key) const;
|
||||
|
||||
// (2)
|
||||
template<typename KeyType>
|
||||
size_type count(KeyType&& key) const;
|
||||
```
|
||||
|
||||
1. Returns the number of elements with key `key`. If `ObjectType` is the default `std::map` type, the return value will
|
||||
always be `0` (`key` was not found) or `1` (`key` was found).
|
||||
2. See 1. This overload is only available if `KeyType` is comparable with `#!cpp typename object_t::key_type` and
|
||||
`#!cpp typename object_comparator_t::is_transparent` denotes a type.
|
||||
|
||||
## Template parameters
|
||||
|
||||
`KeyType`
|
||||
: A type for an object key other than [`json_pointer`](../json_pointer/index.md) that is comparable with
|
||||
[`string_t`](string_t.md) using [`object_comparator_t`](object_comparator_t.md).
|
||||
This can also be a string view (C++17).
|
||||
|
||||
## Parameters
|
||||
|
||||
`key` (in)
|
||||
: key value of the element to count.
|
||||
|
||||
## Return value
|
||||
|
||||
Number of elements with key `key`. If the JSON value is not an object, the return value will be `0`.
|
||||
|
||||
## Exception safety
|
||||
|
||||
Strong exception safety: if an exception occurs, the original value stays intact.
|
||||
|
||||
## Complexity
|
||||
|
||||
Logarithmic in the size of the JSON object.
|
||||
|
||||
## Notes
|
||||
|
||||
This method always returns `0` when executed on a JSON type that is not an object.
|
||||
|
||||
## Examples
|
||||
|
||||
??? example "Example: (1) count number of elements"
|
||||
|
||||
The example shows how `count()` is used.
|
||||
|
||||
```cpp
|
||||
--8<-- "examples/count__object_t_key_type.cpp"
|
||||
```
|
||||
|
||||
Output:
|
||||
|
||||
```json
|
||||
--8<-- "examples/count__object_t_key_type.output"
|
||||
```
|
||||
|
||||
??? example "Example: (2) count number of elements using string_view"
|
||||
|
||||
The example shows how `count()` is used.
|
||||
|
||||
```cpp
|
||||
--8<-- "examples/count__keytype.c++17.cpp"
|
||||
```
|
||||
|
||||
Output:
|
||||
|
||||
```json
|
||||
--8<-- "examples/count__keytype.c++17.output"
|
||||
```
|
||||
|
||||
## See also
|
||||
|
||||
- [find](find.md) find a value in an object
|
||||
- [contains](contains.md) checks whether a key exists
|
||||
|
||||
## Version history
|
||||
|
||||
1. Added in version 3.11.0.
|
||||
2. Added in version 1.0.0. Changed parameter `key` type to `KeyType&&` in version 3.11.0.
|
||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1,115 @@
|
||||
# nlohmann::basic_json::count
|
||||
|
||||
```
|
||||
// (1)
|
||||
size_type count(const typename object_t::key_type& key) const;
|
||||
|
||||
// (2)
|
||||
template<typename KeyType>
|
||||
size_type count(KeyType&& key) const;
|
||||
```
|
||||
|
||||
1. Returns the number of elements with key `key`. If `ObjectType` is the default `std::map` type, the return value will always be `0` (`key` was not found) or `1` (`key` was found).
|
||||
1. See 1. This overload is only available if `KeyType` is comparable with `typename object_t::key_type` and `typename object_comparator_t::is_transparent` denotes a type.
|
||||
|
||||
## Template parameters
|
||||
|
||||
`KeyType` : A type for an object key other than [`json_pointer`](https://json.nlohmann.me/api/json_pointer/index.md) that is comparable with [`string_t`](https://json.nlohmann.me/api/basic_json/string_t/index.md) using [`object_comparator_t`](https://json.nlohmann.me/api/basic_json/object_comparator_t/index.md). This can also be a string view (C++17).
|
||||
|
||||
## Parameters
|
||||
|
||||
`key` (in) : key value of the element to count.
|
||||
|
||||
## Return value
|
||||
|
||||
Number of elements with key `key`. If the JSON value is not an object, the return value will be `0`.
|
||||
|
||||
## Exception safety
|
||||
|
||||
Strong exception safety: if an exception occurs, the original value stays intact.
|
||||
|
||||
## Complexity
|
||||
|
||||
Logarithmic in the size of the JSON object.
|
||||
|
||||
## Notes
|
||||
|
||||
This method always returns `0` when executed on a JSON type that is not an object.
|
||||
|
||||
## Examples
|
||||
|
||||
Example: (1) count number of elements
|
||||
|
||||
The example shows how `count()` is used.
|
||||
|
||||
```
|
||||
#include <iostream>
|
||||
#include <nlohmann/json.hpp>
|
||||
|
||||
using json = nlohmann::json;
|
||||
|
||||
int main()
|
||||
{
|
||||
// create a JSON object
|
||||
json j_object = {{"one", 1}, {"two", 2}};
|
||||
|
||||
// call count()
|
||||
auto count_two = j_object.count("two");
|
||||
auto count_three = j_object.count("three");
|
||||
|
||||
// print values
|
||||
std::cout << "number of elements with key \"two\": " << count_two << '\n';
|
||||
std::cout << "number of elements with key \"three\": " << count_three << '\n';
|
||||
}
|
||||
```
|
||||
|
||||
Output:
|
||||
|
||||
```
|
||||
number of elements with key "two": 1
|
||||
number of elements with key "three": 0
|
||||
```
|
||||
|
||||
Example: (2) count number of elements using string_view
|
||||
|
||||
The example shows how `count()` is used.
|
||||
|
||||
```
|
||||
#include <iostream>
|
||||
#include <string_view>
|
||||
#include <nlohmann/json.hpp>
|
||||
|
||||
using namespace std::string_view_literals;
|
||||
using json = nlohmann::json;
|
||||
|
||||
int main()
|
||||
{
|
||||
// create a JSON object
|
||||
json j_object = {{"one", 1}, {"two", 2}};
|
||||
|
||||
// call count()
|
||||
auto count_two = j_object.count("two"sv);
|
||||
auto count_three = j_object.count("three"sv);
|
||||
|
||||
// print values
|
||||
std::cout << "number of elements with key \"two\": " << count_two << '\n';
|
||||
std::cout << "number of elements with key \"three\": " << count_three << '\n';
|
||||
}
|
||||
```
|
||||
|
||||
Output:
|
||||
|
||||
```
|
||||
number of elements with key "two": 1
|
||||
number of elements with key "three": 0
|
||||
```
|
||||
|
||||
## See also
|
||||
|
||||
- [find](https://json.nlohmann.me/api/basic_json/find/index.md) find a value in an object
|
||||
- [contains](https://json.nlohmann.me/api/basic_json/contains/index.md) checks whether a key exists
|
||||
|
||||
## Version history
|
||||
|
||||
1. Added in version 3.11.0.
|
||||
1. Added in version 1.0.0. Changed parameter `key` type to `KeyType&&` in version 3.11.0.
|
||||
@@ -0,0 +1,41 @@
|
||||
# <small>nlohmann::basic_json::</small>crbegin
|
||||
|
||||
```cpp
|
||||
const_reverse_iterator crbegin() const noexcept;
|
||||
```
|
||||
|
||||
Returns an iterator to the reverse-beginning; that is, the last element.
|
||||
|
||||

|
||||
|
||||
## Return value
|
||||
|
||||
reverse iterator to the last element
|
||||
|
||||
## Exception safety
|
||||
|
||||
No-throw guarantee: this member function never throws exceptions.
|
||||
|
||||
## Complexity
|
||||
|
||||
Constant.
|
||||
|
||||
## Examples
|
||||
|
||||
??? example
|
||||
|
||||
The following code shows an example for `crbegin()`.
|
||||
|
||||
```cpp
|
||||
--8<-- "examples/crbegin.cpp"
|
||||
```
|
||||
|
||||
Output:
|
||||
|
||||
```json
|
||||
--8<-- "examples/crbegin.output"
|
||||
```
|
||||
|
||||
## Version history
|
||||
|
||||
- Added in version 1.0.0.
|
||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1,54 @@
|
||||
# nlohmann::basic_json::crbegin
|
||||
|
||||
```
|
||||
const_reverse_iterator crbegin() const noexcept;
|
||||
```
|
||||
|
||||
Returns an iterator to the reverse-beginning; that is, the last element.
|
||||
|
||||
## Return value
|
||||
|
||||
reverse iterator to the last element
|
||||
|
||||
## Exception safety
|
||||
|
||||
No-throw guarantee: this member function never throws exceptions.
|
||||
|
||||
## Complexity
|
||||
|
||||
Constant.
|
||||
|
||||
## Examples
|
||||
|
||||
Example
|
||||
|
||||
The following code shows an example for `crbegin()`.
|
||||
|
||||
```
|
||||
#include <iostream>
|
||||
#include <nlohmann/json.hpp>
|
||||
|
||||
using json = nlohmann::json;
|
||||
|
||||
int main()
|
||||
{
|
||||
// create an array value
|
||||
json array = {1, 2, 3, 4, 5};
|
||||
|
||||
// get an iterator to the reverse-beginning
|
||||
json::const_reverse_iterator it = array.crbegin();
|
||||
|
||||
// serialize the element that the iterator points to
|
||||
std::cout << *it << '\n';
|
||||
}
|
||||
```
|
||||
|
||||
Output:
|
||||
|
||||
```
|
||||
5
|
||||
```
|
||||
|
||||
## Version history
|
||||
|
||||
- Added in version 1.0.0.
|
||||
@@ -0,0 +1,42 @@
|
||||
# <small>nlohmann::basic_json::</small>crend
|
||||
|
||||
```cpp
|
||||
const_reverse_iterator crend() const noexcept;
|
||||
```
|
||||
|
||||
Returns an iterator to the reverse-end; that is, one before the first element. This element acts as a placeholder,
|
||||
attempting to access it results in undefined behavior.
|
||||
|
||||

|
||||
|
||||
## Return value
|
||||
|
||||
reverse iterator to the element following the last element
|
||||
|
||||
## Exception safety
|
||||
|
||||
No-throw guarantee: this member function never throws exceptions.
|
||||
|
||||
## Complexity
|
||||
|
||||
Constant.
|
||||
|
||||
## Examples
|
||||
|
||||
??? example
|
||||
|
||||
The following code shows an example for `crend()`.
|
||||
|
||||
```cpp
|
||||
--8<-- "examples/crend.cpp"
|
||||
```
|
||||
|
||||
Output:
|
||||
|
||||
```json
|
||||
--8<-- "examples/crend.output"
|
||||
```
|
||||
|
||||
## Version history
|
||||
|
||||
- Added in version 1.0.0.
|
||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1,57 @@
|
||||
# nlohmann::basic_json::crend
|
||||
|
||||
```
|
||||
const_reverse_iterator crend() const noexcept;
|
||||
```
|
||||
|
||||
Returns an iterator to the reverse-end; that is, one before the first element. This element acts as a placeholder, attempting to access it results in undefined behavior.
|
||||
|
||||
## Return value
|
||||
|
||||
reverse iterator to the element following the last element
|
||||
|
||||
## Exception safety
|
||||
|
||||
No-throw guarantee: this member function never throws exceptions.
|
||||
|
||||
## Complexity
|
||||
|
||||
Constant.
|
||||
|
||||
## Examples
|
||||
|
||||
Example
|
||||
|
||||
The following code shows an example for `crend()`.
|
||||
|
||||
```
|
||||
#include <iostream>
|
||||
#include <nlohmann/json.hpp>
|
||||
|
||||
using json = nlohmann::json;
|
||||
|
||||
int main()
|
||||
{
|
||||
// create an array value
|
||||
json array = {1, 2, 3, 4, 5};
|
||||
|
||||
// get an iterator to the reverse-end
|
||||
json::const_reverse_iterator it = array.crend();
|
||||
|
||||
// increment the iterator to point to the first element
|
||||
--it;
|
||||
|
||||
// serialize the element that the iterator points to
|
||||
std::cout << *it << '\n';
|
||||
}
|
||||
```
|
||||
|
||||
Output:
|
||||
|
||||
```
|
||||
1
|
||||
```
|
||||
|
||||
## Version history
|
||||
|
||||
- Added in version 1.0.0.
|
||||
@@ -0,0 +1,35 @@
|
||||
# <small>nlohmann::basic_json::</small>default_object_comparator_t
|
||||
|
||||
```cpp
|
||||
using default_object_comparator_t = std::less<StringType>; // until C++14
|
||||
|
||||
using default_object_comparator_t = std::less<>; // since C++14
|
||||
```
|
||||
|
||||
The default comparator used by [`object_t`](object_t.md).
|
||||
|
||||
Since C++14 a transparent comparator is used which prevents unnecessary string construction
|
||||
when looking up a key in an object.
|
||||
|
||||
The actual comparator used depends on [`object_t`](object_t.md) and can be obtained via
|
||||
[`object_comparator_t`](object_comparator_t.md).
|
||||
|
||||
## Examples
|
||||
|
||||
??? example
|
||||
|
||||
The example below demonstrates the default comparator.
|
||||
|
||||
```cpp
|
||||
--8<-- "examples/default_object_comparator_t.cpp"
|
||||
```
|
||||
|
||||
Output:
|
||||
|
||||
```json
|
||||
--8<-- "examples/default_object_comparator_t.output"
|
||||
```
|
||||
|
||||
## Version history
|
||||
|
||||
- Added in version 3.11.0.
|
||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1,44 @@
|
||||
# nlohmann::basic_json::default_object_comparator_t
|
||||
|
||||
```
|
||||
using default_object_comparator_t = std::less<StringType>; // until C++14
|
||||
|
||||
using default_object_comparator_t = std::less<>; // since C++14
|
||||
```
|
||||
|
||||
The default comparator used by [`object_t`](https://json.nlohmann.me/api/basic_json/object_t/index.md).
|
||||
|
||||
Since C++14 a transparent comparator is used which prevents unnecessary string construction when looking up a key in an object.
|
||||
|
||||
The actual comparator used depends on [`object_t`](https://json.nlohmann.me/api/basic_json/object_t/index.md) and can be obtained via [`object_comparator_t`](https://json.nlohmann.me/api/basic_json/object_comparator_t/index.md).
|
||||
|
||||
## Examples
|
||||
|
||||
Example
|
||||
|
||||
The example below demonstrates the default comparator.
|
||||
|
||||
```
|
||||
#include <iostream>
|
||||
#include <nlohmann/json.hpp>
|
||||
|
||||
using json = nlohmann::json;
|
||||
|
||||
int main()
|
||||
{
|
||||
std::cout << std::boolalpha
|
||||
<< "one < two : " << json::default_object_comparator_t{}("one", "two") << "\n"
|
||||
<< "three < four : " << json::default_object_comparator_t{}("three", "four") << std::endl;
|
||||
}
|
||||
```
|
||||
|
||||
Output:
|
||||
|
||||
```
|
||||
one < two : true
|
||||
three < four : false
|
||||
```
|
||||
|
||||
## Version history
|
||||
|
||||
- Added in version 3.11.0.
|
||||
@@ -0,0 +1,65 @@
|
||||
# <small>nlohmann::basic_json::</small>diff
|
||||
|
||||
```cpp
|
||||
static basic_json diff(const basic_json& source,
|
||||
const basic_json& target);
|
||||
```
|
||||
|
||||
Creates a [JSON Patch](http://jsonpatch.com) so that value `source` can be changed into the value `target` by calling
|
||||
[`patch`](patch.md) function.
|
||||
|
||||
For two JSON values `source` and `target`, the following code yields always `#!cpp true`:
|
||||
```cpp
|
||||
source.patch(diff(source, target)) == target;
|
||||
```
|
||||
|
||||
## Parameters
|
||||
|
||||
`source` (in)
|
||||
: JSON value to compare from
|
||||
|
||||
`target` (in)
|
||||
: JSON value to compare against
|
||||
|
||||
## Return value
|
||||
|
||||
a JSON patch to convert the `source` to `target`
|
||||
|
||||
## Exception safety
|
||||
|
||||
Strong guarantee: if an exception is thrown, there are no changes in the JSON value.
|
||||
|
||||
## Complexity
|
||||
|
||||
Linear in the lengths of `source` and `target`.
|
||||
|
||||
## Notes
|
||||
|
||||
Currently, only `remove`, `add`, and `replace` operations are generated.
|
||||
|
||||
## Examples
|
||||
|
||||
??? example
|
||||
|
||||
The following code shows how a JSON patch is created as a diff for two JSON values.
|
||||
|
||||
```cpp
|
||||
--8<-- "examples/diff.cpp"
|
||||
```
|
||||
|
||||
Output:
|
||||
|
||||
```json
|
||||
--8<-- "examples/diff.output"
|
||||
```
|
||||
|
||||
## See also
|
||||
|
||||
- [RFC 6902 (JSON Patch)](https://tools.ietf.org/html/rfc6902)
|
||||
- [patch](patch.md) applies a JSON Patch
|
||||
- [patch_inplace](patch_inplace.md) applies a JSON Patch in place
|
||||
- [merge_patch](merge_patch.md) applies a JSON Merge Patch
|
||||
|
||||
## Version history
|
||||
|
||||
- Added in version 2.0.0.
|
||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1,123 @@
|
||||
# nlohmann::basic_json::diff
|
||||
|
||||
```
|
||||
static basic_json diff(const basic_json& source,
|
||||
const basic_json& target);
|
||||
```
|
||||
|
||||
Creates a [JSON Patch](http://jsonpatch.com) so that value `source` can be changed into the value `target` by calling [`patch`](https://json.nlohmann.me/api/basic_json/patch/index.md) function.
|
||||
|
||||
For two JSON values `source` and `target`, the following code yields always `true`:
|
||||
|
||||
```
|
||||
source.patch(diff(source, target)) == target;
|
||||
```
|
||||
|
||||
## Parameters
|
||||
|
||||
`source` (in) : JSON value to compare from
|
||||
|
||||
`target` (in) : JSON value to compare against
|
||||
|
||||
## Return value
|
||||
|
||||
a JSON patch to convert the `source` to `target`
|
||||
|
||||
## Exception safety
|
||||
|
||||
Strong guarantee: if an exception is thrown, there are no changes in the JSON value.
|
||||
|
||||
## Complexity
|
||||
|
||||
Linear in the lengths of `source` and `target`.
|
||||
|
||||
## Notes
|
||||
|
||||
Currently, only `remove`, `add`, and `replace` operations are generated.
|
||||
|
||||
## Examples
|
||||
|
||||
Example
|
||||
|
||||
The following code shows how a JSON patch is created as a diff for two JSON values.
|
||||
|
||||
```
|
||||
#include <iostream>
|
||||
#include <iomanip>
|
||||
#include <nlohmann/json.hpp>
|
||||
|
||||
using json = nlohmann::json;
|
||||
using namespace nlohmann::literals;
|
||||
|
||||
int main()
|
||||
{
|
||||
// the source document
|
||||
json source = R"(
|
||||
{
|
||||
"baz": "qux",
|
||||
"foo": "bar"
|
||||
}
|
||||
)"_json;
|
||||
|
||||
// the target document
|
||||
json target = R"(
|
||||
{
|
||||
"baz": "boo",
|
||||
"hello": [
|
||||
"world"
|
||||
]
|
||||
}
|
||||
)"_json;
|
||||
|
||||
// create the patch
|
||||
json patch = json::diff(source, target);
|
||||
|
||||
// roundtrip
|
||||
json patched_source = source.patch(patch);
|
||||
|
||||
// output patch and roundtrip result
|
||||
std::cout << std::setw(4) << patch << "\n\n"
|
||||
<< std::setw(4) << patched_source << std::endl;
|
||||
}
|
||||
```
|
||||
|
||||
Output:
|
||||
|
||||
```
|
||||
[
|
||||
{
|
||||
"op": "replace",
|
||||
"path": "/baz",
|
||||
"value": "boo"
|
||||
},
|
||||
{
|
||||
"op": "remove",
|
||||
"path": "/foo"
|
||||
},
|
||||
{
|
||||
"op": "add",
|
||||
"path": "/hello",
|
||||
"value": [
|
||||
"world"
|
||||
]
|
||||
}
|
||||
]
|
||||
|
||||
{
|
||||
"baz": "boo",
|
||||
"hello": [
|
||||
"world"
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
## See also
|
||||
|
||||
- [RFC 6902 (JSON Patch)](https://tools.ietf.org/html/rfc6902)
|
||||
- [patch](https://json.nlohmann.me/api/basic_json/patch/index.md) applies a JSON Patch
|
||||
- [patch_inplace](https://json.nlohmann.me/api/basic_json/patch_inplace/index.md) applies a JSON Patch in place
|
||||
- [merge_patch](https://json.nlohmann.me/api/basic_json/merge_patch/index.md) applies a JSON Merge Patch
|
||||
|
||||
## Version history
|
||||
|
||||
- Added in version 2.0.0.
|
||||
@@ -0,0 +1,85 @@
|
||||
# <small>nlohmann::basic_json::</small>dump
|
||||
|
||||
```cpp
|
||||
string_t dump(const int indent = -1,
|
||||
const char indent_char = ' ',
|
||||
const bool ensure_ascii = false,
|
||||
const error_handler_t error_handler = error_handler_t::strict) const;
|
||||
```
|
||||
|
||||
Serialization function for JSON values. The function tries to mimic Python's
|
||||
[`json.dumps()` function](https://docs.python.org/2/library/json.html#json.dump), and currently supports its `indent`
|
||||
and `ensure_ascii` parameters.
|
||||
|
||||
## Parameters
|
||||
|
||||
`indent` (in)
|
||||
: If `indent` is nonnegative, then array elements and object members will be pretty-printed with that indent level. An
|
||||
indent level of `0` will only insert newlines. `-1` (the default) selects the most compact representation.
|
||||
|
||||
`indent_char` (in)
|
||||
: The character to use for indentation if `indent` is greater than `0`. The default is ` ` (space).
|
||||
|
||||
`ensure_ascii` (in)
|
||||
: If `ensure_ascii` is true, all non-ASCII characters in the output are escaped with `\uXXXX` sequences, and the
|
||||
result consists of ASCII characters only.
|
||||
|
||||
`error_handler` (in)
|
||||
: how to react on decoding errors; there are three possible values (see [`error_handler_t`](error_handler_t.md):
|
||||
`strict` (throws an exception in case a decoding error occurs; default), `replace` (replace invalid UTF-8 sequences
|
||||
with U+FFFD), and `ignore` (ignore invalid UTF-8 sequences during serialization; all valid bytes are copied to the
|
||||
output unchanged, and invalid bytes are dropped)).
|
||||
|
||||
## Return value
|
||||
|
||||
string containing the serialization of the JSON value
|
||||
|
||||
## Exception safety
|
||||
|
||||
Strong guarantee: if an exception is thrown, there are no changes to any JSON value.
|
||||
|
||||
## Exceptions
|
||||
|
||||
Throws [`type_error.316`](../../home/exceptions.md#jsonexceptiontype_error316) if a string stored inside the JSON value
|
||||
is not UTF-8 encoded and `error_handler` is set to `strict`
|
||||
|
||||
## Complexity
|
||||
|
||||
Linear.
|
||||
|
||||
## Notes
|
||||
|
||||
Binary values are serialized as an object containing two keys:
|
||||
|
||||
- "bytes": an array of bytes as integers
|
||||
- "subtype": the subtype as integer or `#!json null` if the binary has no subtype
|
||||
|
||||
## Examples
|
||||
|
||||
??? example
|
||||
|
||||
The following example shows the effect of different `indent`, `indent_char`, and `ensure_ascii` parameters to the
|
||||
result of the serialization.
|
||||
|
||||
```cpp
|
||||
--8<-- "examples/dump.cpp"
|
||||
```
|
||||
|
||||
Output:
|
||||
|
||||
```json
|
||||
--8<-- "examples/dump.output"
|
||||
```
|
||||
|
||||
## See also
|
||||
|
||||
- [to_string](to_string.md) returns a string representation of a JSON value
|
||||
- [operator<<](../operator_ltlt.md) serialize to stream
|
||||
- [Serialization](../../features/serialization.md) - the serialization article
|
||||
|
||||
## Version history
|
||||
|
||||
- Added in version 1.0.0.
|
||||
- Indentation character `indent_char`, option `ensure_ascii` and exceptions added in version 3.0.0.
|
||||
- Error handlers added in version 3.4.0.
|
||||
- Serialization of binary values added in version 3.8.0.
|
||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1,173 @@
|
||||
# nlohmann::basic_json::dump
|
||||
|
||||
```
|
||||
string_t dump(const int indent = -1,
|
||||
const char indent_char = ' ',
|
||||
const bool ensure_ascii = false,
|
||||
const error_handler_t error_handler = error_handler_t::strict) const;
|
||||
```
|
||||
|
||||
Serialization function for JSON values. The function tries to mimic Python's [`json.dumps()` function](https://docs.python.org/2/library/json.html#json.dump), and currently supports its `indent` and `ensure_ascii` parameters.
|
||||
|
||||
## Parameters
|
||||
|
||||
`indent` (in) : If `indent` is nonnegative, then array elements and object members will be pretty-printed with that indent level. An indent level of `0` will only insert newlines. `-1` (the default) selects the most compact representation.
|
||||
|
||||
`indent_char` (in) : The character to use for indentation if `indent` is greater than `0`. The default is (space).
|
||||
|
||||
`ensure_ascii` (in) : If `ensure_ascii` is true, all non-ASCII characters in the output are escaped with `\uXXXX` sequences, and the result consists of ASCII characters only.
|
||||
|
||||
`error_handler` (in) : how to react on decoding errors; there are three possible values (see [`error_handler_t`](https://json.nlohmann.me/api/basic_json/error_handler_t/index.md): `strict` (throws an exception in case a decoding error occurs; default), `replace` (replace invalid UTF-8 sequences with U+FFFD), and `ignore` (ignore invalid UTF-8 sequences during serialization; all valid bytes are copied to the output unchanged, and invalid bytes are dropped)).
|
||||
|
||||
## Return value
|
||||
|
||||
string containing the serialization of the JSON value
|
||||
|
||||
## Exception safety
|
||||
|
||||
Strong guarantee: if an exception is thrown, there are no changes to any JSON value.
|
||||
|
||||
## Exceptions
|
||||
|
||||
Throws [`type_error.316`](https://json.nlohmann.me/home/exceptions/#jsonexceptiontype_error316) if a string stored inside the JSON value is not UTF-8 encoded and `error_handler` is set to `strict`
|
||||
|
||||
## Complexity
|
||||
|
||||
Linear.
|
||||
|
||||
## Notes
|
||||
|
||||
Binary values are serialized as an object containing two keys:
|
||||
|
||||
- "bytes": an array of bytes as integers
|
||||
- "subtype": the subtype as integer or `null` if the binary has no subtype
|
||||
|
||||
## Examples
|
||||
|
||||
Example
|
||||
|
||||
The following example shows the effect of different `indent`, `indent_char`, and `ensure_ascii` parameters to the result of the serialization.
|
||||
|
||||
```
|
||||
#include <iostream>
|
||||
#include <nlohmann/json.hpp>
|
||||
|
||||
using json = nlohmann::json;
|
||||
|
||||
int main()
|
||||
{
|
||||
// create JSON values
|
||||
json j_object = {{"one", 1}, {"two", 2}};
|
||||
json j_array = {1, 2, 4, 8, 16};
|
||||
json j_string = "Hellö 😀!";
|
||||
|
||||
// call dump()
|
||||
std::cout << "objects:" << '\n'
|
||||
<< j_object.dump() << "\n\n"
|
||||
<< j_object.dump(-1) << "\n\n"
|
||||
<< j_object.dump(0) << "\n\n"
|
||||
<< j_object.dump(4) << "\n\n"
|
||||
<< j_object.dump(1, '\t') << "\n\n";
|
||||
|
||||
std::cout << "arrays:" << '\n'
|
||||
<< j_array.dump() << "\n\n"
|
||||
<< j_array.dump(-1) << "\n\n"
|
||||
<< j_array.dump(0) << "\n\n"
|
||||
<< j_array.dump(4) << "\n\n"
|
||||
<< j_array.dump(1, '\t') << "\n\n";
|
||||
|
||||
std::cout << "strings:" << '\n'
|
||||
<< j_string.dump() << '\n'
|
||||
<< j_string.dump(-1, ' ', true) << '\n';
|
||||
|
||||
// create JSON value with invalid UTF-8 byte sequence
|
||||
json j_invalid = "ä\xA9ü";
|
||||
try
|
||||
{
|
||||
std::cout << j_invalid.dump() << std::endl;
|
||||
}
|
||||
catch (const json::type_error& e)
|
||||
{
|
||||
std::cout << e.what() << std::endl;
|
||||
}
|
||||
|
||||
std::cout << "string with replaced invalid characters: "
|
||||
<< j_invalid.dump(-1, ' ', false, json::error_handler_t::replace)
|
||||
<< "\nstring with ignored invalid characters: "
|
||||
<< j_invalid.dump(-1, ' ', false, json::error_handler_t::ignore)
|
||||
<< '\n';
|
||||
}
|
||||
```
|
||||
|
||||
Output:
|
||||
|
||||
```
|
||||
objects:
|
||||
{"one":1,"two":2}
|
||||
|
||||
{"one":1,"two":2}
|
||||
|
||||
{
|
||||
"one": 1,
|
||||
"two": 2
|
||||
}
|
||||
|
||||
{
|
||||
"one": 1,
|
||||
"two": 2
|
||||
}
|
||||
|
||||
{
|
||||
"one": 1,
|
||||
"two": 2
|
||||
}
|
||||
|
||||
arrays:
|
||||
[1,2,4,8,16]
|
||||
|
||||
[1,2,4,8,16]
|
||||
|
||||
[
|
||||
1,
|
||||
2,
|
||||
4,
|
||||
8,
|
||||
16
|
||||
]
|
||||
|
||||
[
|
||||
1,
|
||||
2,
|
||||
4,
|
||||
8,
|
||||
16
|
||||
]
|
||||
|
||||
[
|
||||
1,
|
||||
2,
|
||||
4,
|
||||
8,
|
||||
16
|
||||
]
|
||||
|
||||
strings:
|
||||
"Hellö 😀!"
|
||||
"Hell\u00f6 \ud83d\ude00!"
|
||||
[json.exception.type_error.316] invalid UTF-8 byte at index 2: 0xA9
|
||||
string with replaced invalid characters: "ä�ü"
|
||||
string with ignored invalid characters: "äü"
|
||||
```
|
||||
|
||||
## See also
|
||||
|
||||
- [to_string](https://json.nlohmann.me/api/basic_json/to_string/index.md) returns a string representation of a JSON value
|
||||
- [operator\<<](https://json.nlohmann.me/api/operator_ltlt/index.md) serialize to stream
|
||||
- [Serialization](https://json.nlohmann.me/features/serialization/index.md) - the serialization article
|
||||
|
||||
## Version history
|
||||
|
||||
- Added in version 1.0.0.
|
||||
- Indentation character `indent_char`, option `ensure_ascii` and exceptions added in version 3.0.0.
|
||||
- Error handlers added in version 3.4.0.
|
||||
- Serialization of binary values added in version 3.8.0.
|
||||
@@ -0,0 +1,71 @@
|
||||
# <small>nlohmann::basic_json::</small>emplace
|
||||
|
||||
```cpp
|
||||
template<class... Args>
|
||||
std::pair<iterator, bool> emplace(Args&& ... args);
|
||||
```
|
||||
|
||||
Inserts a new element into a JSON object constructed in-place with the given `args` if there is no element with the key
|
||||
in the container. If the function is called on a JSON null value, an empty object is created before appending the value
|
||||
created from `args`.
|
||||
|
||||
## Template parameters
|
||||
|
||||
`Args`
|
||||
: compatible types to create a `basic_json` object
|
||||
|
||||
## Iterator invalidation
|
||||
|
||||
For [`ordered_json`](../ordered_json.md), adding a value to an object can yield a reallocation, in which case all
|
||||
iterators (including the `end()` iterator) and all references to the elements are invalidated.
|
||||
|
||||
## Parameters
|
||||
|
||||
`args` (in)
|
||||
: arguments to forward to a constructor of `basic_json`
|
||||
|
||||
## Return value
|
||||
|
||||
a pair consisting of an iterator to the inserted element, or the already-existing element if no insertion happened, and
|
||||
a `#!cpp bool` denoting whether the insertion took place.
|
||||
|
||||
## Exception safety
|
||||
|
||||
Strong guarantee: if an exception is thrown, there are no changes to any JSON value.
|
||||
|
||||
## Exceptions
|
||||
|
||||
Throws [`type_error.311`](../../home/exceptions.md#jsonexceptiontype_error311) when called on a type other than JSON
|
||||
object or `#!json null`; example: `"cannot use emplace() with number"`
|
||||
|
||||
## Complexity
|
||||
|
||||
Logarithmic in the size of the container, O(log(`size()`)).
|
||||
|
||||
## Examples
|
||||
|
||||
??? example
|
||||
|
||||
The example shows how `emplace()` can be used to add elements to a JSON object. Note how the `#!json null` value was
|
||||
silently converted to a JSON object. Further note how no value is added if there was already one value stored with
|
||||
the same key.
|
||||
|
||||
```cpp
|
||||
--8<-- "examples/emplace.cpp"
|
||||
```
|
||||
|
||||
Output:
|
||||
|
||||
```json
|
||||
--8<-- "examples/emplace.output"
|
||||
```
|
||||
|
||||
## See also
|
||||
|
||||
- [emplace_back](emplace_back.md) add a value to an array
|
||||
- [insert](insert.md) add values to an array/object
|
||||
- [Modifying values](../../features/modifying_values.md) - the article on modifying values
|
||||
|
||||
## Version history
|
||||
|
||||
- Since version 2.0.8.
|
||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1,97 @@
|
||||
# nlohmann::basic_json::emplace
|
||||
|
||||
```
|
||||
template<class... Args>
|
||||
std::pair<iterator, bool> emplace(Args&& ... args);
|
||||
```
|
||||
|
||||
Inserts a new element into a JSON object constructed in-place with the given `args` if there is no element with the key in the container. If the function is called on a JSON null value, an empty object is created before appending the value created from `args`.
|
||||
|
||||
## Template parameters
|
||||
|
||||
`Args` : compatible types to create a `basic_json` object
|
||||
|
||||
## Iterator invalidation
|
||||
|
||||
For [`ordered_json`](https://json.nlohmann.me/api/ordered_json/index.md), adding a value to an object can yield a reallocation, in which case all iterators (including the `end()` iterator) and all references to the elements are invalidated.
|
||||
|
||||
## Parameters
|
||||
|
||||
`args` (in) : arguments to forward to a constructor of `basic_json`
|
||||
|
||||
## Return value
|
||||
|
||||
a pair consisting of an iterator to the inserted element, or the already-existing element if no insertion happened, and a `bool` denoting whether the insertion took place.
|
||||
|
||||
## Exception safety
|
||||
|
||||
Strong guarantee: if an exception is thrown, there are no changes to any JSON value.
|
||||
|
||||
## Exceptions
|
||||
|
||||
Throws [`type_error.311`](https://json.nlohmann.me/home/exceptions/#jsonexceptiontype_error311) when called on a type other than JSON object or `null`; example: `"cannot use emplace() with number"`
|
||||
|
||||
## Complexity
|
||||
|
||||
Logarithmic in the size of the container, O(log(`size()`)).
|
||||
|
||||
## Examples
|
||||
|
||||
Example
|
||||
|
||||
The example shows how `emplace()` can be used to add elements to a JSON object. Note how the `null` value was silently converted to a JSON object. Further note how no value is added if there was already one value stored with the same key.
|
||||
|
||||
```
|
||||
#include <iostream>
|
||||
#include <nlohmann/json.hpp>
|
||||
|
||||
using json = nlohmann::json;
|
||||
|
||||
int main()
|
||||
{
|
||||
// create JSON values
|
||||
json object = {{"one", 1}, {"two", 2}};
|
||||
json null;
|
||||
|
||||
// print values
|
||||
std::cout << object << '\n';
|
||||
std::cout << null << '\n';
|
||||
|
||||
// add values
|
||||
auto res1 = object.emplace("three", 3);
|
||||
null.emplace("A", "a");
|
||||
null.emplace("B", "b");
|
||||
|
||||
// the following call will not add an object, because there is already
|
||||
// a value stored at key "B"
|
||||
auto res2 = null.emplace("B", "c");
|
||||
|
||||
// print values
|
||||
std::cout << object << '\n';
|
||||
std::cout << *res1.first << " " << std::boolalpha << res1.second << '\n';
|
||||
|
||||
std::cout << null << '\n';
|
||||
std::cout << *res2.first << " " << std::boolalpha << res2.second << '\n';
|
||||
}
|
||||
```
|
||||
|
||||
Output:
|
||||
|
||||
```
|
||||
{"one":1,"two":2}
|
||||
null
|
||||
{"one":1,"three":3,"two":2}
|
||||
3 true
|
||||
{"A":"a","B":"b"}
|
||||
"b" false
|
||||
```
|
||||
|
||||
## See also
|
||||
|
||||
- [emplace_back](https://json.nlohmann.me/api/basic_json/emplace_back/index.md) add a value to an array
|
||||
- [insert](https://json.nlohmann.me/api/basic_json/insert/index.md) add values to an array/object
|
||||
- [Modifying values](https://json.nlohmann.me/features/modifying_values/index.md) - the article on modifying values
|
||||
|
||||
## Version history
|
||||
|
||||
- Since version 2.0.8.
|
||||
@@ -0,0 +1,66 @@
|
||||
# <small>nlohmann::basic_json::</small>emplace_back
|
||||
|
||||
```cpp
|
||||
template<class... Args>
|
||||
reference emplace_back(Args&& ... args);
|
||||
```
|
||||
|
||||
Creates a JSON value from the passed parameters `args` to the end of the JSON value. If the function is called on a JSON
|
||||
`#!json null` value, an empty array is created before appending the value created from `args`.
|
||||
|
||||
## Template parameters
|
||||
|
||||
`Args`
|
||||
: compatible types to create a `basic_json` object
|
||||
|
||||
## Iterator invalidation
|
||||
|
||||
By adding an element to the end of the array, a reallocation can happen, in which case all iterators (including the
|
||||
[`end()`](end.md) iterator) and all references to the elements are invalidated. Otherwise, only the [`end()`](end.md)
|
||||
iterator is invalidated.
|
||||
|
||||
## Parameters
|
||||
|
||||
`args` (in)
|
||||
: arguments to forward to a constructor of `basic_json`
|
||||
|
||||
## Return value
|
||||
|
||||
reference to the inserted element
|
||||
|
||||
## Exceptions
|
||||
|
||||
Throws [`type_error.311`](../../home/exceptions.md#jsonexceptiontype_error311) when called on a type other than JSON
|
||||
array or `#!json null`; example: `"cannot use emplace_back() with number"`
|
||||
|
||||
## Complexity
|
||||
|
||||
Amortized constant.
|
||||
|
||||
## Examples
|
||||
|
||||
??? example
|
||||
|
||||
The example shows how `emplace_back()` can be used to add elements to a JSON array. Note how the `null` value was
|
||||
silently converted to a JSON array.
|
||||
|
||||
```cpp
|
||||
--8<-- "examples/emplace_back.cpp"
|
||||
```
|
||||
|
||||
Output:
|
||||
|
||||
```json
|
||||
--8<-- "examples/emplace_back.output"
|
||||
```
|
||||
|
||||
## See also
|
||||
|
||||
- [operator+=](operator+=.md) add a value to an array/object
|
||||
- [push_back](push_back.md) add a value to an array/object
|
||||
- [Modifying values](../../features/modifying_values.md) - the article on modifying values
|
||||
|
||||
## Version history
|
||||
|
||||
- Since version 2.0.8.
|
||||
- Returns reference since 3.7.0.
|
||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1,85 @@
|
||||
# nlohmann::basic_json::emplace_back
|
||||
|
||||
```
|
||||
template<class... Args>
|
||||
reference emplace_back(Args&& ... args);
|
||||
```
|
||||
|
||||
Creates a JSON value from the passed parameters `args` to the end of the JSON value. If the function is called on a JSON `null` value, an empty array is created before appending the value created from `args`.
|
||||
|
||||
## Template parameters
|
||||
|
||||
`Args` : compatible types to create a `basic_json` object
|
||||
|
||||
## Iterator invalidation
|
||||
|
||||
By adding an element to the end of the array, a reallocation can happen, in which case all iterators (including the [`end()`](https://json.nlohmann.me/api/basic_json/end/index.md) iterator) and all references to the elements are invalidated. Otherwise, only the [`end()`](https://json.nlohmann.me/api/basic_json/end/index.md) iterator is invalidated.
|
||||
|
||||
## Parameters
|
||||
|
||||
`args` (in) : arguments to forward to a constructor of `basic_json`
|
||||
|
||||
## Return value
|
||||
|
||||
reference to the inserted element
|
||||
|
||||
## Exceptions
|
||||
|
||||
Throws [`type_error.311`](https://json.nlohmann.me/home/exceptions/#jsonexceptiontype_error311) when called on a type other than JSON array or `null`; example: `"cannot use emplace_back() with number"`
|
||||
|
||||
## Complexity
|
||||
|
||||
Amortized constant.
|
||||
|
||||
## Examples
|
||||
|
||||
Example
|
||||
|
||||
The example shows how `emplace_back()` can be used to add elements to a JSON array. Note how the `null` value was silently converted to a JSON array.
|
||||
|
||||
```
|
||||
#include <iostream>
|
||||
#include <nlohmann/json.hpp>
|
||||
|
||||
using json = nlohmann::json;
|
||||
|
||||
int main()
|
||||
{
|
||||
// create JSON values
|
||||
json array = {1, 2, 3, 4, 5};
|
||||
json null;
|
||||
|
||||
// print values
|
||||
std::cout << array << '\n';
|
||||
std::cout << null << '\n';
|
||||
|
||||
// add values
|
||||
array.emplace_back(6);
|
||||
null.emplace_back("first");
|
||||
null.emplace_back(3, "second");
|
||||
|
||||
// print values
|
||||
std::cout << array << '\n';
|
||||
std::cout << null << '\n';
|
||||
}
|
||||
```
|
||||
|
||||
Output:
|
||||
|
||||
```
|
||||
[1,2,3,4,5]
|
||||
null
|
||||
[1,2,3,4,5,6]
|
||||
["first",["second","second","second"]]
|
||||
```
|
||||
|
||||
## See also
|
||||
|
||||
- [operator+=](https://json.nlohmann.me/api/basic_json/operator%2B%3D/index.md) add a value to an array/object
|
||||
- [push_back](https://json.nlohmann.me/api/basic_json/push_back/index.md) add a value to an array/object
|
||||
- [Modifying values](https://json.nlohmann.me/features/modifying_values/index.md) - the article on modifying values
|
||||
|
||||
## Version history
|
||||
|
||||
- Since version 2.0.8.
|
||||
- Returns reference since 3.7.0.
|
||||
@@ -0,0 +1,66 @@
|
||||
# <small>nlohmann::basic_json::</small>empty
|
||||
|
||||
```cpp
|
||||
bool empty() const noexcept;
|
||||
```
|
||||
|
||||
Checks if a JSON value has no elements (i.e., whether its [`size()`](size.md) is `0`).
|
||||
|
||||
## Return value
|
||||
|
||||
The return value depends on the different types and is defined as follows:
|
||||
|
||||
| Value type | return value |
|
||||
|------------|----------------------------------------|
|
||||
| null | `#!cpp true` |
|
||||
| boolean | `#!cpp false` |
|
||||
| string | `#!cpp false` |
|
||||
| number | `#!cpp false` |
|
||||
| binary | `#!cpp false` |
|
||||
| object | result of function `object_t::empty()` |
|
||||
| array | result of function `array_t::empty()` |
|
||||
|
||||
## Exception safety
|
||||
|
||||
No-throw guarantee: this function never throws exceptions.
|
||||
|
||||
## Complexity
|
||||
|
||||
Constant, as long as [`array_t`](array_t.md) and [`object_t`](object_t.md) satisfy the
|
||||
[Container](https://en.cppreference.com/w/cpp/named_req/Container) concept; that is, their `empty()` functions have
|
||||
constant complexity.
|
||||
|
||||
## Possible implementation
|
||||
|
||||
```cpp
|
||||
bool empty() const noexcept
|
||||
{
|
||||
return size() == 0;
|
||||
}
|
||||
```
|
||||
|
||||
## Notes
|
||||
|
||||
This function does not return whether a string stored as JSON value is empty -- it returns whether the JSON container
|
||||
itself is empty which is `#!cpp false` in the case of a string.
|
||||
|
||||
## Examples
|
||||
|
||||
??? example
|
||||
|
||||
The following code uses `empty()` to check if a JSON object contains any elements.
|
||||
|
||||
```cpp
|
||||
--8<-- "examples/empty.cpp"
|
||||
```
|
||||
|
||||
Output:
|
||||
|
||||
```json
|
||||
--8<-- "examples/empty.output"
|
||||
```
|
||||
|
||||
## Version history
|
||||
|
||||
- Added in version 1.0.0.
|
||||
- Extended to return `#!cpp false` for binary types in version 3.8.0.
|
||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1,100 @@
|
||||
# nlohmann::basic_json::empty
|
||||
|
||||
```
|
||||
bool empty() const noexcept;
|
||||
```
|
||||
|
||||
Checks if a JSON value has no elements (i.e., whether its [`size()`](https://json.nlohmann.me/api/basic_json/size/index.md) is `0`).
|
||||
|
||||
## Return value
|
||||
|
||||
The return value depends on the different types and is defined as follows:
|
||||
|
||||
| Value type | return value |
|
||||
| ---------- | -------------------------------------- |
|
||||
| null | `true` |
|
||||
| boolean | `false` |
|
||||
| string | `false` |
|
||||
| number | `false` |
|
||||
| binary | `false` |
|
||||
| object | result of function `object_t::empty()` |
|
||||
| array | result of function `array_t::empty()` |
|
||||
|
||||
## Exception safety
|
||||
|
||||
No-throw guarantee: this function never throws exceptions.
|
||||
|
||||
## Complexity
|
||||
|
||||
Constant, as long as [`array_t`](https://json.nlohmann.me/api/basic_json/array_t/index.md) and [`object_t`](https://json.nlohmann.me/api/basic_json/object_t/index.md) satisfy the [Container](https://en.cppreference.com/w/cpp/named_req/Container) concept; that is, their `empty()` functions have constant complexity.
|
||||
|
||||
## Possible implementation
|
||||
|
||||
```
|
||||
bool empty() const noexcept
|
||||
{
|
||||
return size() == 0;
|
||||
}
|
||||
```
|
||||
|
||||
## Notes
|
||||
|
||||
This function does not return whether a string stored as JSON value is empty -- it returns whether the JSON container itself is empty which is `false` in the case of a string.
|
||||
|
||||
## Examples
|
||||
|
||||
Example
|
||||
|
||||
The following code uses `empty()` to check if a JSON object contains any elements.
|
||||
|
||||
```
|
||||
#include <iostream>
|
||||
#include <nlohmann/json.hpp>
|
||||
|
||||
using json = nlohmann::json;
|
||||
|
||||
int main()
|
||||
{
|
||||
// create JSON values
|
||||
json j_null;
|
||||
json j_boolean = true;
|
||||
json j_number_integer = 17;
|
||||
json j_number_float = 23.42;
|
||||
json j_object = {{"one", 1}, {"two", 2}};
|
||||
json j_object_empty(json::value_t::object);
|
||||
json j_array = {1, 2, 4, 8, 16};
|
||||
json j_array_empty(json::value_t::array);
|
||||
json j_string = "Hello, world";
|
||||
|
||||
// call empty()
|
||||
std::cout << std::boolalpha;
|
||||
std::cout << j_null.empty() << '\n';
|
||||
std::cout << j_boolean.empty() << '\n';
|
||||
std::cout << j_number_integer.empty() << '\n';
|
||||
std::cout << j_number_float.empty() << '\n';
|
||||
std::cout << j_object.empty() << '\n';
|
||||
std::cout << j_object_empty.empty() << '\n';
|
||||
std::cout << j_array.empty() << '\n';
|
||||
std::cout << j_array_empty.empty() << '\n';
|
||||
std::cout << j_string.empty() << '\n';
|
||||
}
|
||||
```
|
||||
|
||||
Output:
|
||||
|
||||
```
|
||||
true
|
||||
false
|
||||
false
|
||||
false
|
||||
false
|
||||
true
|
||||
false
|
||||
true
|
||||
false
|
||||
```
|
||||
|
||||
## Version history
|
||||
|
||||
- Added in version 1.0.0.
|
||||
- Extended to return `false` for binary types in version 3.8.0.
|
||||
@@ -0,0 +1,42 @@
|
||||
# <small>nlohmann::basic_json::</small>end
|
||||
|
||||
```cpp
|
||||
iterator end() noexcept;
|
||||
const_iterator end() const noexcept;
|
||||
```
|
||||
|
||||
Returns an iterator to one past the last element.
|
||||
|
||||

|
||||
|
||||
## Return value
|
||||
|
||||
iterator one past the last element
|
||||
|
||||
## Exception safety
|
||||
|
||||
No-throw guarantee: this member function never throws exceptions.
|
||||
|
||||
## Complexity
|
||||
|
||||
Constant.
|
||||
|
||||
## Examples
|
||||
|
||||
??? example
|
||||
|
||||
The following code shows an example for `end()`.
|
||||
|
||||
```cpp
|
||||
--8<-- "examples/end.cpp"
|
||||
```
|
||||
|
||||
Output:
|
||||
|
||||
```json
|
||||
--8<-- "examples/end.output"
|
||||
```
|
||||
|
||||
## Version history
|
||||
|
||||
- Added in version 1.0.0.
|
||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1,58 @@
|
||||
# nlohmann::basic_json::end
|
||||
|
||||
```
|
||||
iterator end() noexcept;
|
||||
const_iterator end() const noexcept;
|
||||
```
|
||||
|
||||
Returns an iterator to one past the last element.
|
||||
|
||||
## Return value
|
||||
|
||||
iterator one past the last element
|
||||
|
||||
## Exception safety
|
||||
|
||||
No-throw guarantee: this member function never throws exceptions.
|
||||
|
||||
## Complexity
|
||||
|
||||
Constant.
|
||||
|
||||
## Examples
|
||||
|
||||
Example
|
||||
|
||||
The following code shows an example for `end()`.
|
||||
|
||||
```
|
||||
#include <iostream>
|
||||
#include <nlohmann/json.hpp>
|
||||
|
||||
using json = nlohmann::json;
|
||||
|
||||
int main()
|
||||
{
|
||||
// create an array value
|
||||
json array = {1, 2, 3, 4, 5};
|
||||
|
||||
// get an iterator to one past the last element
|
||||
json::iterator it = array.end();
|
||||
|
||||
// decrement the iterator to point to the last element
|
||||
--it;
|
||||
|
||||
// serialize the element that the iterator points to
|
||||
std::cout << *it << '\n';
|
||||
}
|
||||
```
|
||||
|
||||
Output:
|
||||
|
||||
```
|
||||
5
|
||||
```
|
||||
|
||||
## Version history
|
||||
|
||||
- Added in version 1.0.0.
|
||||
@@ -0,0 +1,68 @@
|
||||
# <small>nlohmann::basic_json::</small>end_pos
|
||||
|
||||
```cpp
|
||||
#if JSON_DIAGNOSTIC_POSITIONS
|
||||
constexpr std::size_t end_pos() const noexcept;
|
||||
#endif
|
||||
```
|
||||
|
||||
Returns the position immediately following the last character of the JSON string from which the value was parsed from.
|
||||
|
||||
| JSON type | return value |
|
||||
|-----------|-----------------------------------|
|
||||
| object | position after the closing `}` |
|
||||
| array | position after the closing `]` |
|
||||
| string | position after the closing `"` |
|
||||
| number | position after the last character |
|
||||
| boolean | position after `e` |
|
||||
| null | position after `l` |
|
||||
|
||||
## Return value
|
||||
|
||||
the position of the character _following_ the last character of the given value in the parsed JSON string, if the
|
||||
value was created by the [`parse`](parse.md) function, or `std::string::npos` if the value was constructed otherwise
|
||||
|
||||
## Exception safety
|
||||
|
||||
No-throw guarantee: this member function never throws exceptions.
|
||||
|
||||
## Complexity
|
||||
|
||||
Constant.
|
||||
|
||||
## Notes
|
||||
|
||||
!!! note "Note"
|
||||
|
||||
The function is only available if macro [`JSON_DIAGNOSTIC_POSITIONS`](../macros/json_diagnostic_positions.md) has
|
||||
been defined to `#!cpp 1` before including the library header.
|
||||
|
||||
!!! warning "Invalidation"
|
||||
|
||||
The returned positions are only valid as long as the JSON value is not changed. The positions are *not* updated
|
||||
when the JSON value is changed.
|
||||
|
||||
## Examples
|
||||
|
||||
??? example "Example"
|
||||
|
||||
```cpp
|
||||
--8<-- "examples/diagnostic_positions.cpp"
|
||||
```
|
||||
|
||||
Output:
|
||||
|
||||
```
|
||||
--8<-- "examples/diagnostic_positions.output"
|
||||
```
|
||||
|
||||
The output shows the start/end positions of all the objects and fields in the JSON string.
|
||||
|
||||
## See also
|
||||
|
||||
- [start_pos](start_pos.md) to access the start position
|
||||
- [JSON_DIAGNOSTIC_POSITIONS](../macros/json_diagnostic_positions.md) for an overview of the diagnostic positions
|
||||
|
||||
## Version history
|
||||
|
||||
- Added in version 3.12.0.
|
||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1,163 @@
|
||||
# nlohmann::basic_json::end_pos
|
||||
|
||||
```
|
||||
#if JSON_DIAGNOSTIC_POSITIONS
|
||||
constexpr std::size_t end_pos() const noexcept;
|
||||
#endif
|
||||
```
|
||||
|
||||
Returns the position immediately following the last character of the JSON string from which the value was parsed from.
|
||||
|
||||
| JSON type | return value |
|
||||
| --------- | --------------------------------- |
|
||||
| object | position after the closing `}` |
|
||||
| array | position after the closing `]` |
|
||||
| string | position after the closing `"` |
|
||||
| number | position after the last character |
|
||||
| boolean | position after `e` |
|
||||
| null | position after `l` |
|
||||
|
||||
## Return value
|
||||
|
||||
the position of the character *following* the last character of the given value in the parsed JSON string, if the value was created by the [`parse`](https://json.nlohmann.me/api/basic_json/parse/index.md) function, or `std::string::npos` if the value was constructed otherwise
|
||||
|
||||
## Exception safety
|
||||
|
||||
No-throw guarantee: this member function never throws exceptions.
|
||||
|
||||
## Complexity
|
||||
|
||||
Constant.
|
||||
|
||||
## Notes
|
||||
|
||||
Note
|
||||
|
||||
The function is only available if macro [`JSON_DIAGNOSTIC_POSITIONS`](https://json.nlohmann.me/api/macros/json_diagnostic_positions/index.md) has been defined to `1` before including the library header.
|
||||
|
||||
Invalidation
|
||||
|
||||
The returned positions are only valid as long as the JSON value is not changed. The positions are *not* updated when the JSON value is changed.
|
||||
|
||||
## Examples
|
||||
|
||||
Example
|
||||
|
||||
```
|
||||
#include <iostream>
|
||||
|
||||
#define JSON_DIAGNOSTIC_POSITIONS 1
|
||||
#include <nlohmann/json.hpp>
|
||||
|
||||
using json = nlohmann::json;
|
||||
|
||||
int main()
|
||||
{
|
||||
std::string json_string = R"(
|
||||
{
|
||||
"address": {
|
||||
"street": "Fake Street",
|
||||
"housenumber": 1
|
||||
}
|
||||
}
|
||||
)";
|
||||
json j = json::parse(json_string);
|
||||
|
||||
std::cout << "Root diagnostic positions: \n";
|
||||
std::cout << "\tstart_pos: " << j.start_pos() << '\n';
|
||||
std::cout << "\tend_pos:" << j.end_pos() << "\n";
|
||||
std::cout << "Original string: \n";
|
||||
std::cout << "{\n \"address\": {\n \"street\": \"Fake Street\",\n \"housenumber\": 1\n }\n }" << "\n";
|
||||
std::cout << "Parsed string: \n";
|
||||
std::cout << json_string.substr(j.start_pos(), j.end_pos() - j.start_pos()) << "\n\n";
|
||||
|
||||
std::cout << "address diagnostic positions: \n";
|
||||
std::cout << "\tstart_pos:" << j["address"].start_pos() << '\n';
|
||||
std::cout << "\tend_pos:" << j["address"].end_pos() << "\n\n";
|
||||
std::cout << "Original string: \n";
|
||||
std::cout << "{ \"street\": \"Fake Street\",\n \"housenumber\": 1\n }" << "\n";
|
||||
std::cout << "Parsed string: \n";
|
||||
std::cout << json_string.substr(j["address"].start_pos(), j["address"].end_pos() - j["address"].start_pos()) << "\n\n";
|
||||
|
||||
std::cout << "street diagnostic positions: \n";
|
||||
std::cout << "\tstart_pos:" << j["address"]["street"].start_pos() << '\n';
|
||||
std::cout << "\tend_pos:" << j["address"]["street"].end_pos() << "\n\n";
|
||||
std::cout << "Original string: \n";
|
||||
std::cout << "\"Fake Street\"" << "\n";
|
||||
std::cout << "Parsed string: \n";
|
||||
std::cout << json_string.substr(j["address"]["street"].start_pos(), j["address"]["street"].end_pos() - j["address"]["street"].start_pos()) << "\n\n";
|
||||
|
||||
std::cout << "housenumber diagnostic positions: \n";
|
||||
std::cout << "\tstart_pos:" << j["address"]["housenumber"].start_pos() << '\n';
|
||||
std::cout << "\tend_pos:" << j["address"]["housenumber"].end_pos() << "\n\n";
|
||||
std::cout << "Original string: \n";
|
||||
std::cout << "1" << "\n";
|
||||
std::cout << "Parsed string: \n";
|
||||
std::cout << json_string.substr(j["address"]["housenumber"].start_pos(), j["address"]["housenumber"].end_pos() - j["address"]["housenumber"].start_pos()) << "\n\n";
|
||||
}
|
||||
```
|
||||
|
||||
Output:
|
||||
|
||||
```
|
||||
Root diagnostic positions:
|
||||
start_pos: 5
|
||||
end_pos:109
|
||||
Original string:
|
||||
{
|
||||
"address": {
|
||||
"street": "Fake Street",
|
||||
"housenumber": 1
|
||||
}
|
||||
}
|
||||
Parsed string:
|
||||
{
|
||||
"address": {
|
||||
"street": "Fake Street",
|
||||
"housenumber": 1
|
||||
}
|
||||
}
|
||||
|
||||
address diagnostic positions:
|
||||
start_pos:26
|
||||
end_pos:103
|
||||
|
||||
Original string:
|
||||
{ "street": "Fake Street",
|
||||
"housenumber": 1
|
||||
}
|
||||
Parsed string:
|
||||
{
|
||||
"street": "Fake Street",
|
||||
"housenumber": 1
|
||||
}
|
||||
|
||||
street diagnostic positions:
|
||||
start_pos:50
|
||||
end_pos:63
|
||||
|
||||
Original string:
|
||||
"Fake Street"
|
||||
Parsed string:
|
||||
"Fake Street"
|
||||
|
||||
housenumber diagnostic positions:
|
||||
start_pos:92
|
||||
end_pos:93
|
||||
|
||||
Original string:
|
||||
1
|
||||
Parsed string:
|
||||
1
|
||||
```
|
||||
|
||||
The output shows the start/end positions of all the objects and fields in the JSON string.
|
||||
|
||||
## See also
|
||||
|
||||
- [start_pos](https://json.nlohmann.me/api/basic_json/start_pos/index.md) to access the start position
|
||||
- [JSON_DIAGNOSTIC_POSITIONS](https://json.nlohmann.me/api/macros/json_diagnostic_positions/index.md) for an overview of the diagnostic positions
|
||||
|
||||
## Version history
|
||||
|
||||
- Added in version 3.12.0.
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user