Merge branch 'develop' of https://github.com/nlohmann/json into feature/optional

This commit is contained in:
Niels Lohmann 2020-08-07 09:37:56 +02:00
commit fedf82c904
No known key found for this signature in database
GPG Key ID: 7F3CEA63AE251B69
333 changed files with 16557 additions and 6954 deletions

View File

@ -1,6 +1,6 @@
version: 2 version: 2
jobs: jobs:
build: build_stable:
docker: docker:
- image: debian:stretch - image: debian:stretch
@ -10,15 +10,39 @@ jobs:
- run: - run:
name: Install required tools name: Install required tools
command: 'apt-get update && apt-get install -y gcc g++ git cmake' command: 'apt-get update && apt-get install -y gcc g++ git cmake'
- run:
name: Show versions
command: 'g++ --version ; uname -a; cmake --version'
- run: - run:
name: Run CMake name: Run CMake
command: 'mkdir build ; cd build ; cmake ..' command: 'mkdir build ; cd build ; cmake .. -DJSON_BuildTests=On'
- run: - run:
name: Compile name: Compile
command: 'cmake --build build' command: 'cmake --build build'
- run: - run:
name: Execute test suite name: Execute test suite
command: 'cd build ; ctest --output-on-failure -j 2' command: 'cd build ; ctest --output-on-failure -j 2'
build_bleeding_edge:
docker:
- image: archlinux
steps:
- checkout
- run:
name: Install required tools
command: 'pacman -Sy --noconfirm base base-devel gcc git cmake'
- run:
name: Run CMake
command: 'mkdir build ; cd build ; cmake .. -DJSON_BuildTests=On'
- run:
name: Compile
command: 'cmake --build build'
- run:
name: Execute test suite
command: 'cd build ; ctest --output-on-failure -j 2'
workflows:
version: 2
build_and_test_all:
jobs:
- build_stable
- build_bleeding_edge

84
.clang-format Normal file
View File

@ -0,0 +1,84 @@
#AccessModifierOffset: 2
AlignAfterOpenBracket: Align
AlignConsecutiveAssignments: false
#AlignConsecutiveBitFields: false
AlignConsecutiveDeclarations: false
AlignConsecutiveMacros: false
AlignEscapedNewlines: Right
#AlignOperands: AlignAfterOperator
AlignTrailingComments: true
AllowAllArgumentsOnNextLine: false
AllowAllConstructorInitializersOnNextLine: false
AllowAllParametersOfDeclarationOnNextLine: false
AllowShortBlocksOnASingleLine: Empty
AllowShortCaseLabelsOnASingleLine: false
#AllowShortEnumsOnASingleLine: true
AllowShortFunctionsOnASingleLine: Empty
AllowShortIfStatementsOnASingleLine: Never
AllowShortLambdasOnASingleLine: Empty
AllowShortLoopsOnASingleLine: false
AlwaysBreakAfterReturnType: None
AlwaysBreakBeforeMultilineStrings: false
AlwaysBreakTemplateDeclarations: Yes
BinPackArguments: false
BinPackParameters: false
#BitFieldColonSpacing: Both
BreakBeforeBraces: Custom # or Allman
BraceWrapping:
AfterCaseLabel: true
AfterClass: true
AfterControlStatement: Always
AfterEnum: true
AfterFunction: true
AfterNamespace: false
AfterStruct: true
AfterUnion: true
AfterExternBlock: false
BeforeCatch: true
BeforeElse: true
#BeforeLambdaBody: false
#BeforeWhile: false
SplitEmptyFunction: false
SplitEmptyRecord: false
SplitEmptyNamespace: false
BreakBeforeTernaryOperators: true
BreakConstructorInitializers: BeforeComma
BreakStringLiterals: false
ColumnLimit: 0
CompactNamespaces: false
ConstructorInitializerIndentWidth: 2
Cpp11BracedListStyle: true
PointerAlignment: Left
FixNamespaceComments: true
IncludeBlocks: Preserve
#IndentCaseBlocks: false
IndentCaseLabels: true
IndentGotoLabels: false
IndentPPDirectives: BeforeHash
IndentWidth: 4
KeepEmptyLinesAtTheStartOfBlocks: false
MaxEmptyLinesToKeep: 1
NamespaceIndentation: None
ReflowComments: false
SortIncludes: true
SortUsingDeclarations: true
SpaceAfterCStyleCast: false
SpaceAfterLogicalNot: false
SpaceAfterTemplateKeyword: false
SpaceBeforeAssignmentOperators: true
SpaceBeforeCpp11BracedList: false
SpaceBeforeParens: ControlStatements
SpaceBeforeRangeBasedForLoopColon: true
SpaceBeforeSquareBrackets: false
SpaceInEmptyBlock: false
SpaceInEmptyParentheses: false
SpacesBeforeTrailingComments: 2
SpacesInAngles: false
SpacesInCStyleCastParentheses: false
SpacesInConditionalStatement: false
SpacesInContainerLiterals: false
SpacesInParentheses: false
SpacesInSquareBrackets: false
Standard: c++11
TabWidth: 4
UseTab: Never

View File

@ -1,23 +1,20 @@
Checks: '-*, Checks: '*,
bugprone-*, -cppcoreguidelines-avoid-goto,
cert-*, -cppcoreguidelines-avoid-magic-numbers,
clang-analyzer-*, -cppcoreguidelines-macro-usage,
google-*, -fuchsia-default-arguments-calls,
-google-runtime-references, -fuchsia-default-arguments-declarations,
-fuchsia-overloaded-operator,
-google-explicit-constructor, -google-explicit-constructor,
hicpp-*, -google-runtime-references,
-hicpp-avoid-goto,
-hicpp-explicit-conversions,
-hicpp-no-array-decay, -hicpp-no-array-decay,
-hicpp-uppercase-literal-suffix, -hicpp-uppercase-literal-suffix,
-hicpp-explicit-conversions,
misc-*,
-misc-non-private-member-variables-in-classes,
llvm-*,
-llvm-header-guard, -llvm-header-guard,
modernize-*, -llvm-include-order,
-misc-non-private-member-variables-in-classes,
-modernize-use-trailing-return-type, -modernize-use-trailing-return-type,
performance-*,
portability-*,
readability-*,
-readability-magic-numbers, -readability-magic-numbers,
-readability-uppercase-literal-suffix' -readability-uppercase-literal-suffix'

View File

@ -66,6 +66,6 @@ To make changes, you need to edit the following files:
The following areas really need contribution: 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. - Extending the **continuous integration** toward more exotic compilers such as Android NDK, Intel's Compiler, or the bleeding-edge versions 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. - 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. - 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.

View File

@ -47,7 +47,7 @@ assignees: ''
<!-- Please add an `x` to the respective line. --> <!-- Please add an `x` to the respective line. -->
- [ ] latest release version 3.7.3 - [ ] latest release version 3.9.1
- [ ] other release - please state the version: ___ - [ ] other release - please state the version: ___
- [ ] the `develop` branch - [ ] the `develop` branch

View File

@ -1,17 +0,0 @@
---
name: Feature request
about: Suggest an idea for this project
title: ''
labels: 'kind: enhancement/improvement'
assignees: ''
---
#### Which feature do you want to see in the library?
<!-- Describe the feature in as much detail as possible. -->
#### How would the feature be usable for other users?
<!-- Include sample usage where appropriate. -->

5
.github/ISSUE_TEMPLATE/config.yml vendored Normal file
View File

@ -0,0 +1,5 @@
blank_issues_enabled: false
contact_links:
- name: Ask a question
url: https://github.com/nlohmann/json/discussions
about: Ask questions and discuss with other community members

View File

@ -1,34 +0,0 @@
---
name: Question
about: Ask a question regarding the library.
title: ''
labels: 'kind: question'
assignees: ''
---
#### What do you want to achieve?
<!-- Please describe the feature as detailed as possible. -->
#### What have you tried?
<!-- There are thousands of issues to search: https://github.com/nlohmann/json/issues?q=is%3Aissue+ -->
<!-- There is a full documentation of the API: https://nlohmann.github.io/json/ -->
<!-- There is a detailed README file: https://github.com/nlohmann/json/blob/develop/README.md -->
#### Which compiler and operating system are you using?
<!-- Include as many relevant details about the environment you experienced the bug in. -->
<!-- Make sure you use a supported compiler, see https://github.com/nlohmann/json#supported-compilers. -->
- Compiler: ___
- Operating system: ___
#### Which version of the library did you use?
<!-- Please add an `x` to the respective line. -->
- [ ] latest release version 3.7.3
- [ ] other release - please state the version: ___
- [ ] the `develop` branch

54
.github/workflows/codeql-analysis.yml vendored Normal file
View File

@ -0,0 +1,54 @@
name: "Code scanning - action"
on:
push:
branches: [develop, ]
pull_request:
# The branches below must be a subset of the branches above
branches: [develop]
schedule:
- cron: '0 19 * * 1'
jobs:
CodeQL-Build:
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@v2
with:
# We must fetch at least the immediate parents so that if this is
# a pull request then we can checkout the head.
fetch-depth: 2
# If this run was triggered by a pull request event, then checkout
# the head of the pull request instead of the merge commit.
- run: git checkout HEAD^2
if: ${{ github.event_name == 'pull_request' }}
# Initializes the CodeQL tools for scanning.
- name: Initialize CodeQL
uses: github/codeql-action/init@v1
# Override language selection by uncommenting this and choosing your languages
# with:
# languages: go, javascript, csharp, python, cpp, java
# Autobuild attempts to build any compiled languages (C/C++, C#, or Java).
# If this step fails, then you should remove it and run the build manually (see below)
- name: Autobuild
uses: github/codeql-action/autobuild@v1
# Command-line programs to run using the OS shell.
# 📚 https://git.io/JvXDl
# ✏️ If the Autobuild fails above, remove it and uncomment the following three lines
# and modify them (or add more) to build your code if your project
# uses a compiled language
#- run: |
# make bootstrap
# make release
- name: Perform CodeQL Analysis
uses: github/codeql-action/analyze@v1

View File

@ -10,7 +10,7 @@ jobs:
steps: steps:
- uses: actions/checkout@v1 - uses: actions/checkout@v1
- name: cmake - name: cmake
run: cmake -S . -B build -D CMAKE_BUILD_TYPE=Debug run: cmake -S . -B build -D CMAKE_BUILD_TYPE=Debug -DJSON_BuildTests=On
- name: build - name: build
run: cmake --build build --parallel 10 run: cmake --build build --parallel 10
- name: test - name: test

View File

@ -10,7 +10,7 @@ jobs:
steps: steps:
- uses: actions/checkout@v1 - uses: actions/checkout@v1
- name: cmake - name: cmake
run: cmake -S . -B build -D CMAKE_BUILD_TYPE=Debug run: cmake -S . -B build -D CMAKE_BUILD_TYPE=Debug -DJSON_BuildTests=On
- name: build - name: build
run: cmake --build build --parallel 10 run: cmake --build build --parallel 10
- name: test - name: test

View File

@ -3,15 +3,66 @@ name: Windows
on: [push, pull_request] on: [push, pull_request]
jobs: jobs:
build: msvc2019:
runs-on: windows-latest runs-on: windows-latest
steps: steps:
- uses: actions/checkout@v1 - uses: actions/checkout@v1
- name: cmake - name: cmake
run: cmake -S . -B build -G "Visual Studio 16 2019" -D CMAKE_BUILD_TYPE=Debug run: cmake -S . -B build -G "Visual Studio 16 2019" -D CMAKE_BUILD_TYPE=Debug -DJSON_BuildTests=On
- name: build - name: build
run: cmake --build build --parallel 10 run: cmake --build build --parallel 10
- name: test - name: test
run: cd build ; ctest -j 10 -C Debug --exclude-regex "test-unicode" --output-on-failure run: cd build ; ctest -j 10 -C Debug --exclude-regex "test-unicode" --output-on-failure
clang9:
runs-on: windows-latest
steps:
- uses: actions/checkout@v1
- name: install Clang
run: curl -fsSL -o LLVM9.exe https://releases.llvm.org/9.0.0/LLVM-9.0.0-win64.exe ; 7z x LLVM9.exe -y -o"C:/Program Files/LLVM"
- name: cmake
run: cmake -S . -B build -DCMAKE_CXX_COMPILER="C:/Program Files/LLVM/bin/clang++.exe" -G"MinGW Makefiles" -DCMAKE_BUILD_TYPE=Debug -DJSON_BuildTests=On
- name: build
run: cmake --build build --parallel 10
- name: test
run: cd build ; ctest -j 10 -C Debug --exclude-regex "test-unicode" --output-on-failure
clang10:
runs-on: windows-latest
steps:
- uses: actions/checkout@v1
- name: install Clang
run: curl -fsSL -o LLVM10.exe https://github.com/llvm/llvm-project/releases/download/llvmorg-10.0.0/LLVM-10.0.0-win64.exe ; 7z x LLVM10.exe -y -o"C:/Program Files/LLVM"
- name: cmake
run: cmake -S . -B build -DCMAKE_CXX_COMPILER="C:/Program Files/LLVM/bin/clang++.exe" -G"MinGW Makefiles" -DCMAKE_BUILD_TYPE=Debug -DJSON_BuildTests=On
- name: build
run: cmake --build build --parallel 10
- name: test
run: cd build ; ctest -j 10 -C Debug --exclude-regex "test-unicode" --output-on-failure
clang-cl-10-x64:
runs-on: windows-latest
steps:
- uses: actions/checkout@v1
- name: cmake
run: cmake -S . -B build -G "Visual Studio 16 2019" -A x64 -T ClangCL -DJSON_BuildTests=On
- name: build
run: cmake --build build --config Debug --parallel 10
- name: test
run: cd build ; ctest -j 10 -C Debug --exclude-regex "test-unicode" --output-on-failure
clang-cl-10-x86:
runs-on: windows-latest
steps:
- uses: actions/checkout@v1
- name: cmake
run: cmake -S . -B build -G "Visual Studio 16 2019" -A Win32 -T ClangCL -DJSON_BuildTests=On
- name: build
run: cmake --build build --config Debug --parallel 10
- name: test
run: cd build ; ctest -j 10 -C Debug --exclude-regex "test-unicode" --output-on-failure

9
.gitignore vendored
View File

@ -22,7 +22,14 @@ benchmarks/files/numbers/*.json
.wsjcpp/* .wsjcpp/*
.idea .idea
cmake-build-debug /cmake-build-*
test/test-* test/test-*
/.vs /.vs
doc/mkdocs/venv/
doc/mkdocs/docs/images
doc/mkdocs/docs/examples
doc/mkdocs/site
doc/mkdocs/docs/__pycache__/
doc/xml

View File

@ -10,17 +10,6 @@ sudo: required
group: edge group: edge
###################
# 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 # # build matrix #
################ ################
@ -129,6 +118,9 @@ matrix:
env: env:
- SPECIAL=coverity - SPECIAL=coverity
- COMPILER=clang++-3.6 - COMPILER=clang++-3.6
# 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="
# OSX / Clang # OSX / Clang
@ -150,6 +142,14 @@ matrix:
- os: osx - os: osx
osx_image: xcode11.2 osx_image: xcode11.2
- os: osx
osx_image: xcode12
- os: osx
osx_image: xcode12
env:
- IMPLICIT_CONVERSIONS=OFF
# Linux / GCC # Linux / GCC
- os: linux - os: linux
@ -208,6 +208,16 @@ matrix:
sources: ['ubuntu-toolchain-r-test'] sources: ['ubuntu-toolchain-r-test']
packages: ['g++-9', 'ninja-build'] packages: ['g++-9', 'ninja-build']
- os: linux
compiler: gcc
env:
- COMPILER=g++-9
- IMPLICIT_CONVERSIONS=OFF
addons:
apt:
sources: ['ubuntu-toolchain-r-test']
packages: ['g++-9', 'ninja-build']
- os: linux - os: linux
compiler: gcc compiler: gcc
env: env:
@ -321,14 +331,12 @@ script:
- if [[ "${CXXFLAGS}" != "" ]]; then export CXXFLAGS=${CXXFLAGS}; fi - if [[ "${CXXFLAGS}" != "" ]]; then export CXXFLAGS=${CXXFLAGS}; fi
# by default, use the single-header version # by default, use the single-header version
- if [[ "${MULTIPLE_HEADERS}" == "" ]]; then export MULTIPLE_HEADERS=OFF; fi - if [[ "${MULTIPLE_HEADERS}" == "" ]]; then export MULTIPLE_HEADERS=OFF; fi
# by default, use implicit conversions
# show OS/compiler version - if [[ "${IMPLICIT_CONVERSIONS}" == "" ]]; then export IMPLICIT_CONVERSIONS=ON; fi
- uname -a
- $CXX --version
# compile and execute unit tests # compile and execute unit tests
- mkdir -p build && cd build - mkdir -p build && cd build
- cmake .. ${CMAKE_OPTIONS} -DJSON_MultipleHeaders=${MULTIPLE_HEADERS} -GNinja && cmake --build . --config Release - cmake .. ${CMAKE_OPTIONS} -DJSON_MultipleHeaders=${MULTIPLE_HEADERS} -DJSON_ImplicitConversions=${IMPLICIT_CONVERSIONS} -DJSON_BuildTests=On -GNinja && cmake --build . --config Release
- ctest -C Release --timeout 2700 -V -j - ctest -C Release --timeout 2700 -V -j
- cd .. - cd ..

View File

@ -4,7 +4,7 @@ cmake_minimum_required(VERSION 3.1)
## PROJECT ## PROJECT
## name and version ## name and version
## ##
project(nlohmann_json VERSION 3.7.3 LANGUAGES CXX) project(nlohmann_json VERSION 3.9.1 LANGUAGES CXX)
## ##
## INCLUDE ## INCLUDE
@ -15,9 +15,16 @@ include(ExternalProject)
## ##
## OPTIONS ## OPTIONS
## ##
if (POLICY CMP0077)
# Allow CMake 3.13+ to override options when using FetchContent / add_subdirectory.
cmake_policy(SET CMP0077 NEW)
endif ()
option(JSON_BuildTests "Build the unit tests when BUILD_TESTING is enabled." ON) option(JSON_BuildTests "Build the unit tests when BUILD_TESTING is enabled." ON)
option(JSON_Install "Install CMake targets during install step." ON) option(JSON_Install "Install CMake targets during install step." ON)
option(JSON_MultipleHeaders "Use non-amalgamated version of the library." OFF) option(JSON_MultipleHeaders "Use non-amalgamated version of the library." OFF)
option(JSON_ImplicitConversions "Enable implicit conversions." ON)
## ##
## CONFIGURATION ## CONFIGURATION
@ -33,6 +40,7 @@ set(NLOHMANN_JSON_CMAKE_CONFIG_DIR "${CMAKE_CURRENT_BINARY_DIR}")
set(NLOHMANN_JSON_CMAKE_VERSION_CONFIG_FILE "${NLOHMANN_JSON_CMAKE_CONFIG_DIR}/${PROJECT_NAME}ConfigVersion.cmake") set(NLOHMANN_JSON_CMAKE_VERSION_CONFIG_FILE "${NLOHMANN_JSON_CMAKE_CONFIG_DIR}/${PROJECT_NAME}ConfigVersion.cmake")
set(NLOHMANN_JSON_CMAKE_PROJECT_CONFIG_FILE "${NLOHMANN_JSON_CMAKE_CONFIG_DIR}/${PROJECT_NAME}Config.cmake") set(NLOHMANN_JSON_CMAKE_PROJECT_CONFIG_FILE "${NLOHMANN_JSON_CMAKE_CONFIG_DIR}/${PROJECT_NAME}Config.cmake")
set(NLOHMANN_JSON_CMAKE_PROJECT_TARGETS_FILE "${NLOHMANN_JSON_CMAKE_CONFIG_DIR}/${PROJECT_NAME}Targets.cmake") set(NLOHMANN_JSON_CMAKE_PROJECT_TARGETS_FILE "${NLOHMANN_JSON_CMAKE_CONFIG_DIR}/${PROJECT_NAME}Targets.cmake")
set(NLOHMANN_JSON_PKGCONFIG_INSTALL_DIR "${CMAKE_INSTALL_LIBDIR}/pkgconfig")
if (JSON_MultipleHeaders) if (JSON_MultipleHeaders)
set(NLOHMANN_JSON_INCLUDE_BUILD_DIR "${PROJECT_SOURCE_DIR}/include/") set(NLOHMANN_JSON_INCLUDE_BUILD_DIR "${PROJECT_SOURCE_DIR}/include/")
@ -42,6 +50,10 @@ else()
message(STATUS "Using the single-header code from ${NLOHMANN_JSON_INCLUDE_BUILD_DIR}") message(STATUS "Using the single-header code from ${NLOHMANN_JSON_INCLUDE_BUILD_DIR}")
endif() endif()
if (NOT JSON_ImplicitConversions)
message(STATUS "Implicit conversions are disabled")
endif()
## ##
## TARGET ## TARGET
## create target and add include path ## create target and add include path
@ -54,6 +66,12 @@ else()
target_compile_features(${NLOHMANN_JSON_TARGET_NAME} INTERFACE cxx_std_11) target_compile_features(${NLOHMANN_JSON_TARGET_NAME} INTERFACE cxx_std_11)
endif() endif()
target_compile_definitions(
${NLOHMANN_JSON_TARGET_NAME}
INTERFACE
JSON_USE_IMPLICIT_CONVERSIONS=$<BOOL:${JSON_ImplicitConversions}>
)
target_include_directories( target_include_directories(
${NLOHMANN_JSON_TARGET_NAME} ${NLOHMANN_JSON_TARGET_NAME}
INTERFACE INTERFACE
@ -73,6 +91,12 @@ if (MSVC)
) )
endif() endif()
# Install a pkg-config file, so other tools can find this.
CONFIGURE_FILE(
"${CMAKE_CURRENT_SOURCE_DIR}/cmake/pkg-config.pc.in"
"${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}.pc"
)
## ##
## TESTS ## TESTS
## create and configure the unit test target ## create and configure the unit test target
@ -117,7 +141,7 @@ if(JSON_Install)
FILES ${NLOHMANN_NATVIS_FILE} FILES ${NLOHMANN_NATVIS_FILE}
DESTINATION . DESTINATION .
) )
endif() endif()
export( export(
TARGETS ${NLOHMANN_JSON_TARGET_NAME} TARGETS ${NLOHMANN_JSON_TARGET_NAME}
NAMESPACE ${PROJECT_NAME}:: NAMESPACE ${PROJECT_NAME}::
@ -133,4 +157,8 @@ if(JSON_Install)
NAMESPACE ${PROJECT_NAME}:: NAMESPACE ${PROJECT_NAME}::
DESTINATION ${NLOHMANN_JSON_CONFIG_INSTALL_DIR} DESTINATION ${NLOHMANN_JSON_CONFIG_INSTALL_DIR}
) )
install(
FILES "${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}.pc"
DESTINATION ${NLOHMANN_JSON_PKGCONFIG_INSTALL_DIR}
)
endif() endif()

File diff suppressed because it is too large Load Diff

204
Makefile
View File

@ -5,7 +5,7 @@
########################################################################## ##########################################################################
# directory to recent compiler binaries # directory to recent compiler binaries
COMPILER_DIR=/Users/niels/Documents/projects/compilers/local/bin COMPILER_DIR=/usr/local/opt/llvm/bin
# find GNU sed to use `-i` parameter # find GNU sed to use `-i` parameter
SED:=$(shell command -v gsed || which sed) SED:=$(shell command -v gsed || which sed)
@ -30,7 +30,6 @@ AMALGAMATED_FILE=single_include/nlohmann/json.hpp
all: all:
@echo "amalgamate - amalgamate file single_include/nlohmann/json.hpp from the include/nlohmann sources" @echo "amalgamate - amalgamate file single_include/nlohmann/json.hpp from the include/nlohmann sources"
@echo "ChangeLog.md - generate ChangeLog file" @echo "ChangeLog.md - generate ChangeLog file"
@echo "check - compile and execute test suite"
@echo "check-amalgamation - check whether sources have been amalgamated" @echo "check-amalgamation - check whether sources have been amalgamated"
@echo "clean - remove built files" @echo "clean - remove built files"
@echo "coverage - create coverage information with lcov" @echo "coverage - create coverage information with lcov"
@ -44,38 +43,24 @@ all:
@echo "fuzz_testing_cbor - prepare fuzz testing of the CBOR parser" @echo "fuzz_testing_cbor - prepare fuzz testing of the CBOR parser"
@echo "fuzz_testing_msgpack - prepare fuzz testing of the MessagePack parser" @echo "fuzz_testing_msgpack - prepare fuzz testing of the MessagePack parser"
@echo "fuzz_testing_ubjson - prepare fuzz testing of the UBJSON parser" @echo "fuzz_testing_ubjson - prepare fuzz testing of the UBJSON parser"
@echo "json_unit - create single-file test executable"
@echo "pedantic_clang - run Clang with maximal warning flags" @echo "pedantic_clang - run Clang with maximal warning flags"
@echo "pedantic_gcc - run GCC with maximal warning flags" @echo "pedantic_gcc - run GCC with maximal warning flags"
@echo "pretty - beautify code with Artistic Style" @echo "pretty - beautify code with Artistic Style"
@echo "run_benchmarks - build and run benchmarks" @echo "run_benchmarks - build and run benchmarks"
##########################################################################
# unit tests
##########################################################################
# build unit tests
json_unit:
@$(MAKE) json_unit -C test
# run unit tests
check:
$(MAKE) check -C test
########################################################################## ##########################################################################
# coverage # coverage
########################################################################## ##########################################################################
coverage: coverage:
rm -fr build_coverage rm -fr cmake-build-coverage
mkdir build_coverage mkdir cmake-build-coverage
cd build_coverage ; cmake .. -GNinja -DCMAKE_BUILD_TYPE=Debug -DJSON_Coverage=ON -DJSON_MultipleHeaders=ON cd cmake-build-coverage ; cmake .. -GNinja -DCMAKE_BUILD_TYPE=Debug -DJSON_Coverage=ON -DJSON_MultipleHeaders=ON
cd build_coverage ; ninja cd cmake-build-coverage ; ninja
cd build_coverage ; ctest -j10 cd cmake-build-coverage ; ctest -j10
cd build_coverage ; ninja lcov_html cd cmake-build-coverage ; ninja lcov_html
open build_coverage/test/html/index.html open cmake-build-coverage/test/html/index.html
########################################################################## ##########################################################################
# documentation tests # documentation tests
@ -97,12 +82,13 @@ doctest:
# -Wno-exit-time-destructors: warning in json code triggered by NLOHMANN_JSON_SERIALIZE_ENUM # -Wno-exit-time-destructors: warning in json code triggered by NLOHMANN_JSON_SERIALIZE_ENUM
# -Wno-float-equal: not all comparisons in the tests can be replaced by Approx # -Wno-float-equal: not all comparisons in the tests can be replaced by Approx
# -Wno-keyword-macro: unit-tests use "#define private public" # -Wno-keyword-macro: unit-tests use "#define private public"
# -Wno-missing-prototypes: for NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE
# -Wno-padded: padding is nothing to warn about # -Wno-padded: padding is nothing to warn about
# -Wno-range-loop-analysis: items tests "for(const auto i...)" # -Wno-range-loop-analysis: items tests "for(const auto i...)"
# -Wno-switch-enum -Wno-covered-switch-default: pedantic/contradicting warnings about switches # -Wno-switch-enum -Wno-covered-switch-default: pedantic/contradicting warnings about switches
# -Wno-weak-vtables: exception class is defined inline, but has virtual method # -Wno-weak-vtables: exception class is defined inline, but has virtual method
pedantic_clang: pedantic_clang:
rm -fr build_pedantic rm -fr cmake-build-pedantic
CXXFLAGS=" \ CXXFLAGS=" \
-std=c++11 -Wno-c++98-compat -Wno-c++98-compat-pedantic \ -std=c++11 -Wno-c++98-compat -Wno-c++98-compat-pedantic \
-Werror \ -Werror \
@ -113,24 +99,49 @@ pedantic_clang:
-Wno-exit-time-destructors \ -Wno-exit-time-destructors \
-Wno-float-equal \ -Wno-float-equal \
-Wno-keyword-macro \ -Wno-keyword-macro \
-Wno-missing-prototypes \
-Wno-padded \ -Wno-padded \
-Wno-range-loop-analysis \ -Wno-range-loop-analysis \
-Wno-switch-enum -Wno-covered-switch-default \ -Wno-switch-enum -Wno-covered-switch-default \
-Wno-weak-vtables" cmake -S . -B build_pedantic -GNinja -DCMAKE_BUILD_TYPE=Debug -DJSON_MultipleHeaders=ON -Wno-weak-vtables" cmake -S . -B cmake-build-pedantic -GNinja -DCMAKE_BUILD_TYPE=Debug -DJSON_MultipleHeaders=ON -DJSON_BuildTests=On
cmake --build build_pedantic cmake --build cmake-build-pedantic
# calling GCC with most warnings # calling GCC with most warnings
pedantic_gcc: pedantic_gcc:
rm -fr build_pedantic rm -fr cmake-build-pedantic
CXXFLAGS=" \ CXXFLAGS=" \
-std=c++11 \ -std=c++11 \
-pedantic \
-Werror \
--all-warnings \
--extra-warnings \
-W \
-Wno-abi-tag \
-Waddress \ -Waddress \
-Waddress-of-packed-member \ -Waddress-of-packed-member \
-Wno-aggregate-return \
-Waggressive-loop-optimizations \ -Waggressive-loop-optimizations \
-Waligned-new=all \ -Waligned-new=all \
-Wall \ -Wall \
-Walloc-zero \ -Walloc-zero \
-Walloca \ -Walloca \
-Wanalyzer-double-fclose \
-Wanalyzer-double-free \
-Wanalyzer-exposure-through-output-file \
-Wanalyzer-file-leak \
-Wanalyzer-free-of-non-heap \
-Wanalyzer-malloc-leak \
-Wanalyzer-null-argument \
-Wanalyzer-null-dereference \
-Wanalyzer-possible-null-argument \
-Wanalyzer-possible-null-dereference \
-Wanalyzer-stale-setjmp-buffer \
-Wanalyzer-tainted-array-index \
-Wanalyzer-too-complex \
-Wanalyzer-unsafe-call-within-signal-handler \
-Wanalyzer-use-after-free \
-Wanalyzer-use-of-pointer-in-stale-stack-frame \
-Warith-conversion \
-Warray-bounds \ -Warray-bounds \
-Warray-bounds=2 \ -Warray-bounds=2 \
-Wattribute-alias=2 \ -Wattribute-alias=2 \
@ -140,8 +151,16 @@ pedantic_gcc:
-Wbool-operation \ -Wbool-operation \
-Wbuiltin-declaration-mismatch \ -Wbuiltin-declaration-mismatch \
-Wbuiltin-macro-redefined \ -Wbuiltin-macro-redefined \
-Wc++0x-compat \
-Wc++11-compat \
-Wc++14-compat \
-Wc++17-compat \
-Wc++1z-compat \
-Wc++20-compat \
-Wc++2a-compat \
-Wcannot-profile \ -Wcannot-profile \
-Wcast-align \ -Wcast-align \
-Wcast-align=strict \
-Wcast-function-type \ -Wcast-function-type \
-Wcast-qual \ -Wcast-qual \
-Wcatch-value=3 \ -Wcatch-value=3 \
@ -149,6 +168,7 @@ pedantic_gcc:
-Wclass-conversion \ -Wclass-conversion \
-Wclass-memaccess \ -Wclass-memaccess \
-Wclobbered \ -Wclobbered \
-Wcomma-subscript \
-Wcomment \ -Wcomment \
-Wcomments \ -Wcomments \
-Wconditionally-supported \ -Wconditionally-supported \
@ -175,20 +195,20 @@ pedantic_gcc:
-Wendif-labels \ -Wendif-labels \
-Wenum-compare \ -Wenum-compare \
-Wexpansion-to-defined \ -Wexpansion-to-defined \
-Werror \
-Wextra \ -Wextra \
-Wextra-semi \ -Wextra-semi \
-Wfloat-conversion \ -Wfloat-conversion \
-Wformat \ -Wfloat-equal \
-Wformat-contains-nul \ -Wformat -Wformat-contains-nul \
-Wformat-extra-args \ -Wformat -Wformat-extra-args \
-Wformat-nonliteral \ -Wformat -Wformat-nonliteral \
-Wformat -Wformat-security \
-Wformat -Wformat-y2k \
-Wformat -Wformat-zero-length \
-Wformat-diag \
-Wformat-overflow=2 \ -Wformat-overflow=2 \
-Wformat-security \
-Wformat-signedness \ -Wformat-signedness \
-Wformat-truncation=2 \ -Wformat-truncation=2 \
-Wformat-y2k \
-Wformat-zero-length \
-Wformat=2 \ -Wformat=2 \
-Wframe-address \ -Wframe-address \
-Wfree-nonheap-object \ -Wfree-nonheap-object \
@ -197,6 +217,7 @@ pedantic_gcc:
-Wignored-attributes \ -Wignored-attributes \
-Wignored-qualifiers \ -Wignored-qualifiers \
-Wimplicit-fallthrough=5 \ -Wimplicit-fallthrough=5 \
-Winaccessible-base \
-Winherited-variadic-ctor \ -Winherited-variadic-ctor \
-Winit-list-lifetime \ -Winit-list-lifetime \
-Winit-self \ -Winit-self \
@ -209,33 +230,25 @@ pedantic_gcc:
-Wliteral-suffix \ -Wliteral-suffix \
-Wlogical-not-parentheses \ -Wlogical-not-parentheses \
-Wlogical-op \ -Wlogical-op \
-Wno-long-long \
-Wlto-type-mismatch \ -Wlto-type-mismatch \
-Wmain \ -Wmain \
-Wmaybe-uninitialized \ -Wmaybe-uninitialized \
-Wmemset-elt-size \ -Wmemset-elt-size \
-Wmemset-transposed-args \ -Wmemset-transposed-args \
-Wmisleading-indentation \ -Wmisleading-indentation \
-Wmismatched-tags \
-Wmissing-attributes \ -Wmissing-attributes \
-Wmissing-braces \ -Wmissing-braces \
-Wmissing-declarations \ -Wno-missing-declarations \
-Wmissing-field-initializers \ -Wmissing-field-initializers \
-Wmissing-format-attribute \
-Wmissing-include-dirs \ -Wmissing-include-dirs \
-Wmissing-noreturn \
-Wmissing-profile \ -Wmissing-profile \
-Wmultichar \ -Wmultichar \
-Wmultiple-inheritance \ -Wmultiple-inheritance \
-Wmultistatement-macros \ -Wmultistatement-macros \
-Wnarrowing \
-Wno-deprecated-declarations \
-Wno-float-equal \
-Wno-long-long \
-Wno-namespaces \ -Wno-namespaces \
-Wno-padded \ -Wnarrowing \
-Wno-switch-enum \
-Wno-system-headers \
-Wno-templates \
-Wno-undef \
-Wno-noexcept \ -Wno-noexcept \
-Wnoexcept-type \ -Wnoexcept-type \
-Wnon-template-friend \ -Wnon-template-friend \
@ -243,7 +256,7 @@ pedantic_gcc:
-Wnonnull \ -Wnonnull \
-Wnonnull-compare \ -Wnonnull-compare \
-Wnonportable-cfstrings \ -Wnonportable-cfstrings \
-Wnormalized \ -Wnormalized=nfkc \
-Wnull-dereference \ -Wnull-dereference \
-Wodr \ -Wodr \
-Wold-style-cast \ -Wold-style-cast \
@ -254,6 +267,7 @@ pedantic_gcc:
-Wpacked \ -Wpacked \
-Wpacked-bitfield-compat \ -Wpacked-bitfield-compat \
-Wpacked-not-aligned \ -Wpacked-not-aligned \
-Wno-padded \
-Wparentheses \ -Wparentheses \
-Wpedantic \ -Wpedantic \
-Wpessimizing-move \ -Wpessimizing-move \
@ -266,6 +280,7 @@ pedantic_gcc:
-Wpsabi \ -Wpsabi \
-Wredundant-decls \ -Wredundant-decls \
-Wredundant-move \ -Wredundant-move \
-Wredundant-tags \
-Wregister \ -Wregister \
-Wreorder \ -Wreorder \
-Wrestrict \ -Wrestrict \
@ -273,9 +288,6 @@ pedantic_gcc:
-Wreturn-type \ -Wreturn-type \
-Wscalar-storage-order \ -Wscalar-storage-order \
-Wsequence-point \ -Wsequence-point \
-Wshadow \
-Wshadow-compatible-local \
-Wshadow-local \
-Wshadow=compatible-local \ -Wshadow=compatible-local \
-Wshadow=global \ -Wshadow=global \
-Wshadow=local \ -Wshadow=local \
@ -291,9 +303,13 @@ pedantic_gcc:
-Wsizeof-pointer-div \ -Wsizeof-pointer-div \
-Wsizeof-pointer-memaccess \ -Wsizeof-pointer-memaccess \
-Wstack-protector \ -Wstack-protector \
-Wstrict-aliasing \
-Wstrict-aliasing=3 \ -Wstrict-aliasing=3 \
-Wstrict-null-sentinel \ -Wstrict-null-sentinel \
-Wstrict-overflow \
-Wstrict-overflow=5 \ -Wstrict-overflow=5 \
-Wstring-compare \
-Wstringop-overflow \
-Wstringop-overflow=4 \ -Wstringop-overflow=4 \
-Wstringop-truncation \ -Wstringop-truncation \
-Wsubobject-linkage \ -Wsubobject-linkage \
@ -309,14 +325,19 @@ pedantic_gcc:
-Wswitch \ -Wswitch \
-Wswitch-bool \ -Wswitch-bool \
-Wswitch-default \ -Wswitch-default \
-Wno-switch-enum \
-Wswitch-outside-range \
-Wswitch-unreachable \ -Wswitch-unreachable \
-Wsync-nand \ -Wsync-nand \
-Wsynth \ -Wsynth \
-Wno-system-headers \
-Wtautological-compare \ -Wtautological-compare \
-Wno-templates \
-Wterminate \ -Wterminate \
-Wtrampolines \ -Wtrampolines \
-Wtrigraphs \ -Wtrigraphs \
-Wtype-limits \ -Wtype-limits \
-Wundef \
-Wuninitialized \ -Wuninitialized \
-Wunknown-pragmas \ -Wunknown-pragmas \
-Wunreachable-code \ -Wunreachable-code \
@ -327,7 +348,7 @@ pedantic_gcc:
-Wunused-const-variable=2 \ -Wunused-const-variable=2 \
-Wunused-function \ -Wunused-function \
-Wunused-label \ -Wunused-label \
-Wunused-local-typedefs \ -Wno-unused-local-typedefs \
-Wunused-macros \ -Wunused-macros \
-Wunused-parameter \ -Wunused-parameter \
-Wunused-result \ -Wunused-result \
@ -340,22 +361,24 @@ pedantic_gcc:
-Wvirtual-inheritance \ -Wvirtual-inheritance \
-Wvirtual-move-assign \ -Wvirtual-move-assign \
-Wvla \ -Wvla \
-Wvolatile \
-Wvolatile-register-var \ -Wvolatile-register-var \
-Wwrite-strings \ -Wwrite-strings \
-Wzero-as-null-pointer-constant \ -Wzero-as-null-pointer-constant \
" cmake -S . -B build_pedantic -GNinja -DCMAKE_BUILD_TYPE=Debug -DJSON_MultipleHeaders=ON -Wzero-length-bounds \
cmake --build build_pedantic " cmake -S . -B cmake-build-pedantic -GNinja -DCMAKE_BUILD_TYPE=Debug -DJSON_MultipleHeaders=ON -DJSON_BuildTests=On
cmake --build cmake-build-pedantic
########################################################################## ##########################################################################
# benchmarks # benchmarks
########################################################################## ##########################################################################
run_benchmarks: run_benchmarks:
rm -fr build_benchmarks rm -fr cmake-build-benchmarks
mkdir build_benchmarks mkdir cmake-build-benchmarks
cd build_benchmarks ; cmake ../benchmarks -GNinja -DCMAKE_BUILD_TYPE=Release cd cmake-build-benchmarks ; cmake ../benchmarks -GNinja -DCMAKE_BUILD_TYPE=Release -DJSON_BuildTests=On
cd build_benchmarks ; ninja cd cmake-build-benchmarks ; ninja
cd build_benchmarks ; ./json_benchmarks cd cmake-build-benchmarks ; ./json_benchmarks
########################################################################## ##########################################################################
# fuzzing # fuzzing
@ -428,14 +451,14 @@ cppcheck:
# call Clang Static Analyzer <https://clang-analyzer.llvm.org> # call Clang Static Analyzer <https://clang-analyzer.llvm.org>
clang_analyze: clang_analyze:
rm -fr clang_analyze_build rm -fr cmake-build-clang-analyze
mkdir clang_analyze_build mkdir cmake-build-clang-analyze
cd clang_analyze_build ; CCC_CXX=$(COMPILER_DIR)/clang++ CXX=$(COMPILER_DIR)/clang++ $(COMPILER_DIR)/scan-build cmake .. -GNinja cd cmake-build-clang-analyze ; CCC_CXX=$(COMPILER_DIR)/clang++ CXX=$(COMPILER_DIR)/clang++ $(COMPILER_DIR)/scan-build cmake .. -GNinja -DJSON_BuildTests=On
cd clang_analyze_build ; \ cd cmake-build-clang-analyze ; \
$(COMPILER_DIR)/scan-build \ $(COMPILER_DIR)/scan-build \
-enable-checker alpha.core.BoolAssignment,alpha.core.CallAndMessageUnInitRefArg,alpha.core.CastSize,alpha.core.CastToStruct,alpha.core.Conversion,alpha.core.DynamicTypeChecker,alpha.core.FixedAddr,alpha.core.PointerArithm,alpha.core.PointerSub,alpha.core.SizeofPtr,alpha.core.StackAddressAsyncEscape,alpha.core.TestAfterDivZero,alpha.deadcode.UnreachableCode,core.builtin.BuiltinFunctions,core.builtin.NoReturnFunctions,core.CallAndMessage,core.DivideZero,core.DynamicTypePropagation,core.NonnilStringConstants,core.NonNullParamChecker,core.NullDereference,core.StackAddressEscape,core.UndefinedBinaryOperatorResult,core.uninitialized.ArraySubscript,core.uninitialized.Assign,core.uninitialized.Branch,core.uninitialized.CapturedBlockVariable,core.uninitialized.UndefReturn,core.VLASize,cplusplus.InnerPointer,cplusplus.Move,cplusplus.NewDelete,cplusplus.NewDeleteLeaks,cplusplus.SelfAssignment,deadcode.DeadStores,nullability.NullableDereferenced,nullability.NullablePassedToNonnull,nullability.NullableReturnedFromNonnull,nullability.NullPassedToNonnull,nullability.NullReturnedFromNonnull \ -enable-checker alpha.core.BoolAssignment,alpha.core.CallAndMessageUnInitRefArg,alpha.core.CastSize,alpha.core.CastToStruct,alpha.core.Conversion,alpha.core.DynamicTypeChecker,alpha.core.FixedAddr,alpha.core.PointerArithm,alpha.core.PointerSub,alpha.core.SizeofPtr,alpha.core.StackAddressAsyncEscape,alpha.core.TestAfterDivZero,alpha.deadcode.UnreachableCode,core.builtin.BuiltinFunctions,core.builtin.NoReturnFunctions,core.CallAndMessage,core.DivideZero,core.DynamicTypePropagation,core.NonnilStringConstants,core.NonNullParamChecker,core.NullDereference,core.StackAddressEscape,core.UndefinedBinaryOperatorResult,core.uninitialized.ArraySubscript,core.uninitialized.Assign,core.uninitialized.Branch,core.uninitialized.CapturedBlockVariable,core.uninitialized.UndefReturn,core.VLASize,cplusplus.InnerPointer,cplusplus.Move,cplusplus.NewDelete,cplusplus.NewDeleteLeaks,cplusplus.SelfAssignment,deadcode.DeadStores,nullability.NullableDereferenced,nullability.NullablePassedToNonnull,nullability.NullableReturnedFromNonnull,nullability.NullPassedToNonnull,nullability.NullReturnedFromNonnull \
--use-c++=$(COMPILER_DIR)/clang++ -analyze-headers -o report ninja --use-c++=$(COMPILER_DIR)/clang++ -analyze-headers -o report ninja
open clang_analyze_build/report/*/index.html open cmake-build-clang-analyze/report/*/index.html
# call cpplint <https://github.com/cpplint/cpplint> # call cpplint <https://github.com/cpplint/cpplint>
# Note: some errors expected due to false positives # Note: some errors expected due to false positives
@ -446,22 +469,22 @@ cpplint:
# call Clang-Tidy <https://clang.llvm.org/extra/clang-tidy/> # call Clang-Tidy <https://clang.llvm.org/extra/clang-tidy/>
clang_tidy: clang_tidy:
$(COMPILER_DIR)/clang-tidy $(AMALGAMATED_FILE) -- -Iinclude -std=c++11 $(COMPILER_DIR)/clang-tidy $(SRCS) -- -Iinclude -std=c++11
# call PVS-Studio Analyzer <https://www.viva64.com/en/pvs-studio/> # call PVS-Studio Analyzer <https://www.viva64.com/en/pvs-studio/>
pvs_studio: pvs_studio:
rm -fr pvs_studio_build rm -fr cmake-build-pvs-studio
mkdir pvs_studio_build mkdir cmake-build-pvs-studio
cd pvs_studio_build ; cmake .. -DCMAKE_EXPORT_COMPILE_COMMANDS=On cd cmake-build-pvs-studio ; cmake .. -DCMAKE_EXPORT_COMPILE_COMMANDS=On -DJSON_MultipleHeaders=ON
cd pvs_studio_build ; pvs-studio-analyzer analyze -j 10 cd cmake-build-pvs-studio ; pvs-studio-analyzer analyze -j 10
cd pvs_studio_build ; plog-converter -a'GA:1,2;64:1;CS' -t fullhtml PVS-Studio.log -o pvs cd cmake-build-pvs-studio ; plog-converter -a'GA:1,2;64:1;CS' -t fullhtml PVS-Studio.log -o pvs
open pvs_studio_build/pvs/index.html open cmake-build-pvs-studio/pvs/index.html
# call Infer <https://fbinfer.com> static analyzer # call Infer <https://fbinfer.com> static analyzer
infer: infer:
rm -fr infer_build rm -fr cmake-build-infer
mkdir infer_build mkdir cmake-build-infer
cd infer_build ; infer compile -- cmake .. ; infer run -- make -j 4 cd cmake-build-infer ; infer compile -- cmake .. -DJSON_MultipleHeaders=ON ; infer run -- make -j 4
# call OCLint <http://oclint.org> static analyzer # call OCLint <http://oclint.org> static analyzer
oclint: oclint:
@ -470,11 +493,11 @@ oclint:
# execute the test suite with Clang sanitizers (address and undefined behavior) # execute the test suite with Clang sanitizers (address and undefined behavior)
clang_sanitize: clang_sanitize:
rm -fr clang_sanitize_build rm -fr cmake-build-clang-sanitize
mkdir clang_sanitize_build mkdir cmake-build-clang-sanitize
cd clang_sanitize_build ; CXX=$(COMPILER_DIR)/clang++ cmake .. -DJSON_Sanitizer=On -DJSON_MultipleHeaders=ON -GNinja cd cmake-build-clang-sanitize ; CXX=$(COMPILER_DIR)/clang++ cmake .. -DJSON_Sanitizer=On -DJSON_MultipleHeaders=ON -DJSON_BuildTests=On -GNinja
cd clang_sanitize_build ; ninja cd cmake-build-clang-sanitize ; ninja
cd clang_sanitize_build ; ctest -j10 cd cmake-build-clang-sanitize ; ctest -j10
########################################################################## ##########################################################################
@ -502,7 +525,11 @@ pretty:
--preserve-date \ --preserve-date \
--suffix=none \ --suffix=none \
--formatted \ --formatted \
$(SRCS) $(AMALGAMATED_FILE) test/src/*.cpp benchmarks/src/benchmarks.cpp doc/examples/*.cpp $(SRCS) $(AMALGAMATED_FILE) test/src/*.cpp test/src/*.hpp benchmarks/src/benchmarks.cpp doc/examples/*.cpp
# call the Clang-Format on all source files
pretty_format:
for FILE in $(SRCS) $(AMALGAMATED_FILE) test/src/*.cpp test/src/*.hpp benchmarks/src/benchmarks.cpp doc/examples/*.cpp; do echo $$FILE; clang-format -i $$FILE; done
# create single header file # create single header file
amalgamate: $(AMALGAMATED_FILE) amalgamate: $(AMALGAMATED_FILE)
@ -524,7 +551,7 @@ check-amalgamation:
check-single-includes: check-single-includes:
@for x in $(SRCS); do \ @for x in $(SRCS); do \
echo "Checking self-sufficiency of $$x..." ; \ echo "Checking self-sufficiency of $$x..." ; \
echo "#include <$$x>\nint main() {}\n" | sed 's|include/||' > single_include_test.cpp; \ echo "#include <$$x>\nint main() {}\n" | $(SED) 's|include/||' > single_include_test.cpp; \
$(CXX) $(CXXFLAGS) -Iinclude -std=c++11 single_include_test.cpp -o single_include_test; \ $(CXX) $(CXXFLAGS) -Iinclude -std=c++11 single_include_test.cpp -o single_include_test; \
rm -f single_include_test.cpp single_include_test; \ rm -f single_include_test.cpp single_include_test; \
done done
@ -534,17 +561,17 @@ check-single-includes:
# CMake # CMake
########################################################################## ##########################################################################
# grep "^option" CMakeLists.txt test/CMakeLists.txt | sed 's/(/ /' | awk '{print $2}' | xargs # grep "^option" CMakeLists.txt test/CMakeLists.txt | $(SED) 's/(/ /' | awk '{print $2}' | xargs
# check if all flags of our CMake files work # check if all flags of our CMake files work
check_cmake_flags_do: check_cmake_flags_do:
$(CMAKE_BINARY) --version $(CMAKE_BINARY) --version
for flag in '' JSON_BuildTests JSON_Install JSON_MultipleHeaders JSON_Sanitizer JSON_Valgrind JSON_NoExceptions JSON_Coverage; do \ for flag in JSON_BuildTests JSON_Install JSON_MultipleHeaders JSON_Sanitizer JSON_Valgrind JSON_NoExceptions JSON_Coverage; do \
rm -fr cmake_build; \ rm -fr cmake_build; \
mkdir cmake_build; \ mkdir cmake_build; \
echo "$(CMAKE_BINARY) .. -D$$flag=On" ; \ echo "\n\n$(CMAKE_BINARY) .. -D$$flag=On\n" ; \
cd cmake_build ; \ cd cmake_build ; \
CXX=g++-8 $(CMAKE_BINARY) .. -D$$flag=On -DCMAKE_CXX_COMPILE_FEATURES="cxx_std_11;cxx_range_for" -DCMAKE_CXX_FLAGS="-std=gnu++11" ; \ $(CMAKE_BINARY) -Werror=dev .. -D$$flag=On -DCMAKE_CXX_COMPILE_FEATURES="cxx_std_11;cxx_range_for" -DCMAKE_CXX_FLAGS="-std=gnu++11" ; \
test -f Makefile || exit 1 ; \ test -f Makefile || exit 1 ; \
cd .. ; \ cd .. ; \
done; done;
@ -602,9 +629,8 @@ clean:
rm -fr json_unit json_benchmarks fuzz fuzz-testing *.dSYM test/*.dSYM oclint_report.html rm -fr json_unit json_benchmarks fuzz fuzz-testing *.dSYM test/*.dSYM oclint_report.html
rm -fr benchmarks/files/numbers/*.json rm -fr benchmarks/files/numbers/*.json
rm -fr cmake-3.1.0-Darwin64.tar.gz cmake-3.1.0-Darwin64 rm -fr cmake-3.1.0-Darwin64.tar.gz cmake-3.1.0-Darwin64
rm -fr build_coverage build_benchmarks fuzz-testing clang_analyze_build pvs_studio_build infer_build clang_sanitize_build cmake_build rm -fr cmake-build-coverage cmake-build-benchmarks fuzz-testing cmake-build-clang-analyze cmake-build-pvs-studio cmake-build-infer cmake-build-clang-sanitize cmake_build
$(MAKE) clean -Cdoc $(MAKE) clean -Cdoc
$(MAKE) clean -Ctest
########################################################################## ##########################################################################
# Thirdparty code # Thirdparty code
@ -613,6 +639,6 @@ clean:
update_hedley: update_hedley:
rm -f include/nlohmann/thirdparty/hedley/hedley.hpp include/nlohmann/thirdparty/hedley/hedley_undef.hpp rm -f include/nlohmann/thirdparty/hedley/hedley.hpp include/nlohmann/thirdparty/hedley/hedley_undef.hpp
curl https://raw.githubusercontent.com/nemequ/hedley/master/hedley.h -o include/nlohmann/thirdparty/hedley/hedley.hpp curl https://raw.githubusercontent.com/nemequ/hedley/master/hedley.h -o include/nlohmann/thirdparty/hedley/hedley.hpp
gsed -i 's/HEDLEY_/JSON_HEDLEY_/g' include/nlohmann/thirdparty/hedley/hedley.hpp $(SED) -i 's/HEDLEY_/JSON_HEDLEY_/g' include/nlohmann/thirdparty/hedley/hedley.hpp
grep "[[:blank:]]*#[[:blank:]]*undef" include/nlohmann/thirdparty/hedley/hedley.hpp | grep -v "__" | sort | uniq | gsed 's/ //g' | gsed 's/undef/undef /g' > include/nlohmann/thirdparty/hedley/hedley_undef.hpp grep "[[:blank:]]*#[[:blank:]]*undef" include/nlohmann/thirdparty/hedley/hedley.hpp | grep -v "__" | sort | uniq | $(SED) 's/ //g' | $(SED) 's/undef/undef /g' > include/nlohmann/thirdparty/hedley/hedley_undef.hpp
$(MAKE) amalgamate $(MAKE) amalgamate

228
README.md
View File

@ -12,13 +12,13 @@
[![Language grade: C/C++](https://img.shields.io/lgtm/grade/cpp/g/nlohmann/json.svg?logo=lgtm&logoWidth=18)](https://lgtm.com/projects/g/nlohmann/json/context:cpp) [![Language grade: C/C++](https://img.shields.io/lgtm/grade/cpp/g/nlohmann/json.svg?logo=lgtm&logoWidth=18)](https://lgtm.com/projects/g/nlohmann/json/context:cpp)
[![Fuzzing Status](https://oss-fuzz-build-logs.storage.googleapis.com/badges/json.svg)](https://bugs.chromium.org/p/oss-fuzz/issues/list?sort=-opened&can=1&q=proj:json) [![Fuzzing Status](https://oss-fuzz-build-logs.storage.googleapis.com/badges/json.svg)](https://bugs.chromium.org/p/oss-fuzz/issues/list?sort=-opened&can=1&q=proj:json)
[![Try online](https://img.shields.io/badge/try-online-blue.svg)](https://wandbox.org/permlink/3lCHrFUZANONKv7a) [![Try online](https://img.shields.io/badge/try-online-blue.svg)](https://wandbox.org/permlink/3lCHrFUZANONKv7a)
[![Documentation](https://img.shields.io/badge/docs-doxygen-blue.svg)](http://nlohmann.github.io/json) [![Documentation](https://img.shields.io/badge/docs-doxygen-blue.svg)](https://nlohmann.github.io/json/doxygen/index.html)
[![GitHub license](https://img.shields.io/badge/license-MIT-blue.svg)](https://raw.githubusercontent.com/nlohmann/json/master/LICENSE.MIT) [![GitHub license](https://img.shields.io/badge/license-MIT-blue.svg)](https://raw.githubusercontent.com/nlohmann/json/master/LICENSE.MIT)
[![FOSSA Status](https://app.fossa.com/api/projects/git%2Bgithub.com%2Fnlohmann%2Fjson.svg?type=shield)](https://app.fossa.com/projects/git%2Bgithub.com%2Fnlohmann%2Fjson?ref=badge_shield) [![FOSSA Status](https://app.fossa.com/api/projects/git%2Bgithub.com%2Fnlohmann%2Fjson.svg?type=shield)](https://app.fossa.com/projects/git%2Bgithub.com%2Fnlohmann%2Fjson?ref=badge_shield)
[![GitHub Releases](https://img.shields.io/github/release/nlohmann/json.svg)](https://github.com/nlohmann/json/releases) [![GitHub Releases](https://img.shields.io/github/release/nlohmann/json.svg)](https://github.com/nlohmann/json/releases)
[![GitHub Downloads](https://img.shields.io/github/downloads/nlohmann/json/total)](https://github.com/nlohmann/json/releases) [![GitHub Downloads](https://img.shields.io/github/downloads/nlohmann/json/total)](https://github.com/nlohmann/json/releases)
[![GitHub Issues](https://img.shields.io/github/issues/nlohmann/json.svg)](http://github.com/nlohmann/json/issues) [![GitHub Issues](https://img.shields.io/github/issues/nlohmann/json.svg)](https://github.com/nlohmann/json/issues)
[![Average time to resolve an issue](http://isitmaintained.com/badge/resolution/nlohmann/json.svg)](http://isitmaintained.com/project/nlohmann/json "Average time to resolve an issue") [![Average time to resolve an issue](https://isitmaintained.com/badge/resolution/nlohmann/json.svg)](https://isitmaintained.com/project/nlohmann/json "Average time to resolve an issue")
[![CII Best Practices](https://bestpractices.coreinfrastructure.org/projects/289/badge)](https://bestpractices.coreinfrastructure.org/projects/289) [![CII Best Practices](https://bestpractices.coreinfrastructure.org/projects/289/badge)](https://bestpractices.coreinfrastructure.org/projects/289)
[![GitHub Sponsors](https://img.shields.io/badge/GitHub-Sponsors-ff69b4)](https://github.com/sponsors/nlohmann) [![GitHub Sponsors](https://img.shields.io/badge/GitHub-Sponsors-ff69b4)](https://github.com/sponsors/nlohmann)
@ -27,6 +27,7 @@
- [Integration](#integration) - [Integration](#integration)
- [CMake](#cmake) - [CMake](#cmake)
- [Package Managers](#package-managers) - [Package Managers](#package-managers)
- [Pkg-config](#pkg-config)
- [Examples](#examples) - [Examples](#examples)
- [JSON as first-class data type](#json-as-first-class-data-type) - [JSON as first-class data type](#json-as-first-class-data-type)
- [Serialization / Deserialization](#serialization--deserialization) - [Serialization / Deserialization](#serialization--deserialization)
@ -55,7 +56,7 @@ There are myriads of [JSON](https://json.org) libraries out there, and each may
- **Trivial integration**. Our whole code consists of a single header file [`json.hpp`](https://github.com/nlohmann/json/blob/develop/single_include/nlohmann/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. - **Trivial integration**. Our whole code consists of a single header file [`json.hpp`](https://github.com/nlohmann/json/blob/develop/single_include/nlohmann/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/tree/develop/test/src) and covers [100%](https://coveralls.io/r/nlohmann/json) of the code, including all exceptional behavior. Furthermore, we checked with [Valgrind](http://valgrind.org) and the [Clang Sanitizers](https://clang.llvm.org/docs/index.html) that there are no memory leaks. [Google OSS-Fuzz](https://github.com/google/oss-fuzz/tree/master/projects/json) additionally runs fuzz tests against all parsers 24/7, effectively executing billions of tests so far. To maintain high quality, the project is following the [Core Infrastructure Initiative (CII) best practices](https://bestpractices.coreinfrastructure.org/projects/289). - **Serious testing**. Our class is heavily [unit-tested](https://github.com/nlohmann/json/tree/develop/test/src) and covers [100%](https://coveralls.io/r/nlohmann/json) of the code, including all exceptional behavior. Furthermore, we checked with [Valgrind](https://valgrind.org) and the [Clang Sanitizers](https://clang.llvm.org/docs/index.html) that there are no memory leaks. [Google OSS-Fuzz](https://github.com/google/oss-fuzz/tree/master/projects/json) additionally runs fuzz tests against all parsers 24/7, effectively executing billions of tests so far. 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: Other aspects were not so important to us:
@ -148,7 +149,7 @@ Example:
include(FetchContent) include(FetchContent)
FetchContent_Declare(json FetchContent_Declare(json
GIT_REPOSITORY https://github.com/nlohmann/json GIT_REPOSITORY https://github.com/nlohmann/json.git
GIT_TAG v3.7.3) GIT_TAG v3.7.3)
FetchContent_GetProperties(json) FetchContent_GetProperties(json)
@ -199,9 +200,9 @@ endif()
### Package Managers ### Package Managers
: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`. :beer: If you are using OS X and [Homebrew](https://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`.
If you are using the [Meson Build System](http://mesonbuild.com), add this source tree as a [meson subproject](https://mesonbuild.com/Subprojects.html#using-a-subproject). You may also use the `include.zip` published in this project's [Releases](https://github.com/nlohmann/json/releases) to reduce the size of the vendored source tree. Alternatively, you can get a wrap file by downloading it from [Meson WrapDB](https://wrapdb.mesonbuild.com/nlohmann_json), or simply use `meson wrap install nlohmann_json`. Please see the meson project for any issues regarding the packaging. If you are using the [Meson Build System](https://mesonbuild.com), add this source tree as a [meson subproject](https://mesonbuild.com/Subprojects.html#using-a-subproject). You may also use the `include.zip` published in this project's [Releases](https://github.com/nlohmann/json/releases) to reduce the size of the vendored source tree. Alternatively, you can get a wrap file by downloading it from [Meson WrapDB](https://wrapdb.mesonbuild.com/nlohmann_json), or simply use `meson wrap install nlohmann_json`. Please see the meson project for any issues regarding the packaging.
The provided meson.build can also be used as an alternative to cmake for installing `nlohmann_json` system-wide in which case a pkg-config file is installed. To use it, simply have your build system require the `nlohmann_json` pkg-config dependency. In Meson, it is preferred to use the [`dependency()`](https://mesonbuild.com/Reference-manual.html#dependency) object with a subproject fallback, rather than using the subproject directly. The provided meson.build can also be used as an alternative to cmake for installing `nlohmann_json` system-wide in which case a pkg-config file is installed. To use it, simply have your build system require the `nlohmann_json` pkg-config dependency. In Meson, it is preferred to use the [`dependency()`](https://mesonbuild.com/Reference-manual.html#dependency) object with a subproject fallback, rather than using the subproject directly.
@ -215,7 +216,7 @@ If you are using [Buckaroo](https://buckaroo.pm), you can install this library's
If you are using [vcpkg](https://github.com/Microsoft/vcpkg/) on your project for external dependencies, then you can use the [nlohmann-json package](https://github.com/Microsoft/vcpkg/tree/master/ports/nlohmann-json). Please see the vcpkg project for any issues regarding the packaging. If you are using [vcpkg](https://github.com/Microsoft/vcpkg/) on your project for external dependencies, then you can use the [nlohmann-json package](https://github.com/Microsoft/vcpkg/tree/master/ports/nlohmann-json). Please see the vcpkg project for any issues regarding the packaging.
If you are using [cget](http://cget.readthedocs.io/en/latest/), you can install the latest development version with `cget install nlohmann/json`. A specific version can be installed with `cget install nlohmann/json@v3.1.0`. Also, the multiple header version can be installed by adding the `-DJSON_MultipleHeaders=ON` flag (i.e., `cget install nlohmann/json -DJSON_MultipleHeaders=ON`). If you are using [cget](https://cget.readthedocs.io/en/latest/), you can install the latest development version with `cget install nlohmann/json`. A specific version can be installed with `cget install nlohmann/json@v3.1.0`. Also, the multiple header version can be installed by adding the `-DJSON_MultipleHeaders=ON` flag (i.e., `cget install nlohmann/json -DJSON_MultipleHeaders=ON`).
If you are using [CocoaPods](https://cocoapods.org), you can use the library by adding pod `"nlohmann_json", '~>3.1.2'` to your podfile (see [an example](https://bitbucket.org/benman/nlohmann_json-cocoapod/src/master/)). Please file issues [here](https://bitbucket.org/benman/nlohmann_json-cocoapod/issues?status=new&status=open). If you are using [CocoaPods](https://cocoapods.org), you can use the library by adding pod `"nlohmann_json", '~>3.1.2'` to your podfile (see [an example](https://bitbucket.org/benman/nlohmann_json-cocoapod/src/master/)). Please file issues [here](https://bitbucket.org/benman/nlohmann_json-cocoapod/issues?status=new&status=open).
@ -223,12 +224,26 @@ If you are using [NuGet](https://www.nuget.org), you can use the package [nlohma
If you are using [conda](https://conda.io/), you can use the package [nlohmann_json](https://github.com/conda-forge/nlohmann_json-feedstock) from [conda-forge](https://conda-forge.org) executing `conda install -c conda-forge nlohmann_json`. Please file issues [here](https://github.com/conda-forge/nlohmann_json-feedstock/issues). If you are using [conda](https://conda.io/), you can use the package [nlohmann_json](https://github.com/conda-forge/nlohmann_json-feedstock) from [conda-forge](https://conda-forge.org) executing `conda install -c conda-forge nlohmann_json`. Please file issues [here](https://github.com/conda-forge/nlohmann_json-feedstock/issues).
If you are using [MSYS2](http://www.msys2.org/), your can use the [mingw-w64-nlohmann-json](https://packages.msys2.org/base/mingw-w64-nlohmann-json) package, just type `pacman -S mingw-w64-i686-nlohmann-json` or `pacman -S mingw-w64-x86_64-nlohmann-json` for installation. Please file issues [here](https://github.com/msys2/MINGW-packages/issues/new?title=%5Bnlohmann-json%5D) if you experience problems with the packages. If you are using [MSYS2](https://www.msys2.org/), your can use the [mingw-w64-nlohmann-json](https://packages.msys2.org/base/mingw-w64-nlohmann-json) package, just type `pacman -S mingw-w64-i686-nlohmann-json` or `pacman -S mingw-w64-x86_64-nlohmann-json` for installation. Please file issues [here](https://github.com/msys2/MINGW-packages/issues/new?title=%5Bnlohmann-json%5D) if you experience problems with the packages.
If you are using [`build2`](https://build2.org), you can use the [`nlohmann-json`](https://cppget.org/nlohmann-json) package from the public repository http://cppget.org or directly from the [package's sources repository](https://github.com/build2-packaging/nlohmann-json). In your project's `manifest` file, just add `depends: nlohmann-json` (probably with some [version constraints](https://build2.org/build2-toolchain/doc/build2-toolchain-intro.xhtml#guide-add-remove-deps)). If you are not familiar with using dependencies in `build2`, [please read this introduction](https://build2.org/build2-toolchain/doc/build2-toolchain-intro.xhtml). If you are using [`build2`](https://build2.org), you can use the [`nlohmann-json`](https://cppget.org/nlohmann-json) package from the public repository https://cppget.org or directly from the [package's sources repository](https://github.com/build2-packaging/nlohmann-json). In your project's `manifest` file, just add `depends: nlohmann-json` (probably with some [version constraints](https://build2.org/build2-toolchain/doc/build2-toolchain-intro.xhtml#guide-add-remove-deps)). If you are not familiar with using dependencies in `build2`, [please read this introduction](https://build2.org/build2-toolchain/doc/build2-toolchain-intro.xhtml).
Please file issues [here](https://github.com/build2-packaging/nlohmann-json) if you experience problems with the packages. Please file issues [here](https://github.com/build2-packaging/nlohmann-json) if you experience problems with the packages.
If you are using [`wsjcpp`](http://wsjcpp.org), you can use the command `wsjcpp install "https://github.com/nlohmann/json:develop"` to get the latest version. Note you can change the branch ":develop" to an existing tag or another branch. If you are using [`wsjcpp`](https://wsjcpp.org), you can use the command `wsjcpp install "https://github.com/nlohmann/json:develop"` to get the latest version. Note you can change the branch ":develop" to an existing tag or another branch.
### Pkg-config
If you are using bare Makefiles, you can use `pkg-config` to generate the include flags that point to where the library is installed:
```sh
pkg-config nlohmann_json --cflags
```
Users of the Meson build system will also be able to use a system wide library, which will be found by `pkg-config`:
```meson
json = dependency('nlohmann_json', required: true)
```
## Examples ## Examples
@ -416,7 +431,7 @@ Please note that setting the exception bit for `failbit` is inappropriate for th
#### Read from iterator range #### Read from iterator range
You can also parse JSON from an iterator range; that is, from any container accessible by iterators whose content is stored as contiguous byte sequence, for instance a `std::vector<std::uint8_t>`: You can also parse JSON from an iterator range; that is, from any container accessible by iterators whose `value_type` is an integral type of 1, 2 or 4 bytes, which will be interpreted as UTF-8, UTF-16 and UTF-32 respectively. For instance, a `std::vector<std::uint8_t>`, or a `std::list<std::uint16_t>`:
```cpp ```cpp
std::vector<std::uint8_t> v = {'t', 'r', 'u', 'e'}; std::vector<std::uint8_t> v = {'t', 'r', 'u', 'e'};
@ -430,6 +445,53 @@ std::vector<std::uint8_t> v = {'t', 'r', 'u', 'e'};
json j = json::parse(v); json j = json::parse(v);
``` ```
#### Custom data source
Since the parse function accepts arbitrary iterator ranges, you can provide your own data sources by implementing the `LegacyInputIterator` concept.
```cpp
struct MyContainer {
void advance();
const char& get_current();
};
struct MyIterator {
using difference_type = std::ptrdiff_t;
using value_type = char;
using pointer = const char*;
using reference = const char&;
using iterator_category = std::input_iterator_tag;
MyIterator& operator++() {
MyContainer.advance();
return *this;
}
bool operator!=(const MyIterator& rhs) const {
return rhs.target != target;
}
reference operator*() const {
return target.get_current();
}
MyContainer* target = nullptr;
};
MyIterator begin(MyContainer& tgt) {
return MyIterator{&tgt};
}
MyIterator end(const MyContainer&) {
return {};
}
void foo() {
MyContainer c;
json j = json::parse(c);
}
```
#### SAX interface #### SAX interface
The library uses a SAX-like interface with the following functions: The library uses a SAX-like interface with the following functions:
@ -450,6 +512,8 @@ bool number_float(number_float_t val, const string_t& s);
// called when a string is parsed; value is passed and can be safely moved away // called when a string is parsed; value is passed and can be safely moved away
bool string(string_t& val); bool string(string_t& val);
// called when a binary value is parsed; value is passed and can be safely moved away
bool binary(binary_t& val);
// called when an object or array begins or ends, resp. The number of elements is passed (or -1 if not known) // called when an object or array begins or ends, resp. The number of elements is passed (or -1 if not known)
bool start_object(std::size_t elements); bool start_object(std::size_t elements);
@ -544,6 +608,11 @@ for (auto& [key, value] : o.items()) {
} }
// find an entry // find an entry
if (o.contains("foo")) {
// there is an entry with key "foo"
}
// or via find and an iterator
if (o.find("foo") != o.end()) { if (o.find("foo") != o.end()) {
// there is an entry with key "foo" // there is an entry with key "foo"
} }
@ -695,6 +764,7 @@ Supported types can be implicitly converted to JSON values.
It is recommended to **NOT USE** implicit conversions **FROM** a JSON value. It is recommended to **NOT USE** implicit conversions **FROM** a JSON value.
You can find more details about this recommendation [here](https://www.github.com/nlohmann/json/issues/958). You can find more details about this recommendation [here](https://www.github.com/nlohmann/json/issues/958).
You can switch off implicit conversions by defining `JSON_USE_IMPLICIT_CONVERSIONS` to `0` before including the `json.hpp` header. When using CMake, you can also achieve this by setting the option `JSON_ImplicitConversions` to `OFF`.
```cpp ```cpp
// strings // strings
@ -817,6 +887,42 @@ Some important things:
* In function `from_json`, use function [`at()`](https://nlohmann.github.io/json/classnlohmann_1_1basic__json_a93403e803947b86f4da2d1fb3345cf2c.html#a93403e803947b86f4da2d1fb3345cf2c) to access the object values rather than `operator[]`. In case a key does not exist, `at` throws an exception that you can handle, whereas `operator[]` exhibits undefined behavior. * In function `from_json`, use function [`at()`](https://nlohmann.github.io/json/classnlohmann_1_1basic__json_a93403e803947b86f4da2d1fb3345cf2c.html#a93403e803947b86f4da2d1fb3345cf2c) to access the object values rather than `operator[]`. In case a key does not exist, `at` throws an exception that you can handle, whereas `operator[]` exhibits undefined behavior.
* You do not need to add serializers or deserializers for STL types like `std::vector`: the library already implements these. * You do not need to add serializers or deserializers for STL types like `std::vector`: the library already implements these.
#### Simplify your life with macros
If you just want to serialize/deserialize some structs, the `to_json`/`from_json` functions can be a lot of boilerplate.
There are two macros to make your life easier as long as you (1) want to use a JSON object as serialization and (2) want to use the member variable names as object keys in that object:
- `NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE(name, member1, member2, ...)` is to be defined inside of the namespace of the class/struct to create code for.
- `NLOHMANN_DEFINE_TYPE_INTRUSIVE(name, member1, member2, ...)` is to be defined inside of the class/struct to create code for. This macro can also access private members.
In both macros, the first parameter is the name of the class/struct, and all remaining parameters name the members.
##### Examples
The `to_json`/`from_json` functions for the `person` struct above can be created with:
```cpp
namespace ns {
NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE(person, name, address, age)
}
```
Here is an example with private members, where `NLOHMANN_DEFINE_TYPE_INTRUSIVE` is needed:
```cpp
namespace ns {
class address {
private:
std::string street;
int housenumber;
int postcode;
public:
NLOHMANN_DEFINE_TYPE_INTRUSIVE(address, street, housenumber, postcode)
};
}
```
#### How do I convert third-party types? #### How do I convert third-party types?
@ -1011,7 +1117,7 @@ Other Important points:
### Binary formats (BSON, CBOR, MessagePack, and UBJSON) ### Binary formats (BSON, CBOR, MessagePack, and UBJSON)
Though JSON is a ubiquitous data format, it is not a very compact format suitable for data exchange, for instance over a network. Hence, the library supports [BSON](http://bsonspec.org) (Binary JSON), [CBOR](http://cbor.io) (Concise Binary Object Representation), [MessagePack](http://msgpack.org), and [UBJSON](http://ubjson.org) (Universal Binary JSON Specification) to efficiently encode JSON values to byte vectors and to decode such vectors. Though JSON is a ubiquitous data format, it is not a very compact format suitable for data exchange, for instance over a network. Hence, the library supports [BSON](http://bsonspec.org) (Binary JSON), [CBOR](https://cbor.io) (Concise Binary Object Representation), [MessagePack](https://msgpack.org), and [UBJSON](http://ubjson.org) (Universal Binary JSON Specification) to efficiently encode JSON values to byte vectors and to decode such vectors.
```cpp ```cpp
// create a JSON value // create a JSON value
@ -1085,8 +1191,9 @@ auto cbor = json::to_msgpack(j); // 0xD5 (fixext2), 0x10, 0xCA, 0xFE
Though it's 2020 already, the support for C++11 is still a bit sparse. Currently, the following compilers are known to work: Though it's 2020 already, the support for C++11 is still a bit sparse. Currently, the following compilers are known to work:
- GCC 4.8 - 10.0 (and possibly later) - GCC 4.8 - 10.1 (and possibly later)
- Clang 3.4 - 10.0 (and possibly later) - Clang 3.4 - 10.0 (and possibly later)
- Apple Clang 9.1 - 12.0 (and possibly later)
- Intel C++ Compiler 17.0.2 (and possibly later) - Intel C++ Compiler 17.0.2 (and possibly later)
- Microsoft Visual C++ 2015 / Build Tools 14.0.25123.0 (and possibly later) - Microsoft Visual C++ 2015 / Build Tools 14.0.25123.0 (and possibly later)
- Microsoft Visual C++ 2017 / Build Tools 15.5.180.51428 (and possibly later) - Microsoft Visual C++ 2017 / Build Tools 15.5.180.51428 (and possibly later)
@ -1107,7 +1214,7 @@ Please note:
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. 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` or `strtof`) 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). - For GCC running on MinGW or Android SDK, the error `'to_string' is not a member of 'std'` (or similarly, for `strtod` or `strtof`) 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](https://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).
- Unsupported versions of GCC and Clang are rejected by `#error` directives. This can be switched off by defining `JSON_SKIP_UNSUPPORTED_COMPILER_CHECK`. Note that you can expect no support in this case. - Unsupported versions of GCC and Clang are rejected by `#error` directives. This can be switched off by defining `JSON_SKIP_UNSUPPORTED_COMPILER_CHECK`. Note that you can expect no support in this case.
@ -1122,6 +1229,7 @@ The following compilers are currently used in continuous integration at [Travis]
| Apple Clang 10.0.1 (clang-1001.0.46.4); Xcode 10.2.1 | macOS 10.14.4 | Travis | | Apple Clang 10.0.1 (clang-1001.0.46.4); Xcode 10.2.1 | macOS 10.14.4 | Travis |
| Apple Clang 11.0.0 (clang-1100.0.33.12); Xcode 11.2.1 | macOS 10.14.6 | Travis | | Apple Clang 11.0.0 (clang-1100.0.33.12); Xcode 11.2.1 | macOS 10.14.6 | Travis |
| Apple Clang 11.0.3 (clang-1103.0.32.59); Xcode 11.4.1 | macOS 10.15.4 | GitHub Actions | | Apple Clang 11.0.3 (clang-1103.0.32.59); Xcode 11.4.1 | macOS 10.15.4 | GitHub Actions |
| Apple Clang 12.0.0 (clang-1200.0.22.7); Xcode 11.4.1 | macOS 10.15.5 | Travis |
| Clang 3.5.0 (3.5.0-4ubuntu2~trusty2) | Ubuntu 14.04.5 LTS | Travis | | Clang 3.5.0 (3.5.0-4ubuntu2~trusty2) | Ubuntu 14.04.5 LTS | Travis |
| Clang 3.6.2 (3.6.2-svn240577-1~exp1) | Ubuntu 14.04.5 LTS | Travis | | Clang 3.6.2 (3.6.2-svn240577-1~exp1) | Ubuntu 14.04.5 LTS | Travis |
| Clang 3.7.1 (3.7.1-svn253571-1~exp1) | Ubuntu 14.04.5 LTS | Travis | | Clang 3.7.1 (3.7.1-svn253571-1~exp1) | Ubuntu 14.04.5 LTS | Travis |
@ -1132,6 +1240,8 @@ The following compilers are currently used in continuous integration at [Travis]
| Clang 6.0.1 (6.0.1-svn334776-1~exp1~20190309042707.121) | Ubuntu 14.04.5 LTS | Travis | | Clang 6.0.1 (6.0.1-svn334776-1~exp1~20190309042707.121) | Ubuntu 14.04.5 LTS | Travis |
| Clang 7.1.0 (7.1.0-svn353565-1~exp1~20190419134007.64) | Ubuntu 14.04.5 LTS | Travis | | Clang 7.1.0 (7.1.0-svn353565-1~exp1~20190419134007.64) | Ubuntu 14.04.5 LTS | Travis |
| Clang 7.5.0 (Ubuntu 7.5.0-3ubuntu1~18.04) | Ubuntu 18.04.4 LTS | Travis | | Clang 7.5.0 (Ubuntu 7.5.0-3ubuntu1~18.04) | Ubuntu 18.04.4 LTS | Travis |
| Clang 9.0.0 (x86_64-pc-windows-msvc) | Windows-10.0.17763 | GitHub Actions |
| Clang 10.0.0 (x86_64-pc-windows-msvc) | Windows-10.0.17763 | GitHub Actions |
| GCC 4.8.5 (Ubuntu 4.8.5-4ubuntu8~14.04.2) | Ubuntu 14.04.5 LTS | Travis | | GCC 4.8.5 (Ubuntu 4.8.5-4ubuntu8~14.04.2) | Ubuntu 14.04.5 LTS | Travis |
| GCC 4.9.4 (Ubuntu 4.9.4-2ubuntu1~14.04.1) | Ubuntu 14.04.5 LTS | Travis | | GCC 4.9.4 (Ubuntu 4.9.4-2ubuntu1~14.04.1) | Ubuntu 14.04.5 LTS | Travis |
| GCC 5.5.0 (Ubuntu 5.5.0-12ubuntu1~14.04) | Ubuntu 14.04.5 LTS | Travis | | GCC 5.5.0 (Ubuntu 5.5.0-12ubuntu1~14.04) | Ubuntu 14.04.5 LTS | Travis |
@ -1142,10 +1252,12 @@ The following compilers are currently used in continuous integration at [Travis]
| GCC 7.5.0 (Ubuntu 7.5.0-3ubuntu1~18.04) | Ubuntu 18.04.4 LTS | GitHub Actions | | GCC 7.5.0 (Ubuntu 7.5.0-3ubuntu1~18.04) | Ubuntu 18.04.4 LTS | GitHub Actions |
| GCC 8.4.0 (Ubuntu 8.4.0-1ubuntu1~14.04) | Ubuntu 14.04.5 LTS | Travis | | GCC 8.4.0 (Ubuntu 8.4.0-1ubuntu1~14.04) | Ubuntu 14.04.5 LTS | Travis |
| GCC 9.3.0 (Ubuntu 9.3.0-11ubuntu0~14.04) | Ubuntu 14.04.5 LTS | Travis | | GCC 9.3.0 (Ubuntu 9.3.0-11ubuntu0~14.04) | Ubuntu 14.04.5 LTS | Travis |
| GCC 10.1.0 (Arch Linux latest) | Arch Linux | Circle CI |
| MSVC 19.0.24241.7 (Build Engine version 14.0.25420.1) | Windows-6.3.9600 | AppVeyor | | MSVC 19.0.24241.7 (Build Engine version 14.0.25420.1) | Windows-6.3.9600 | AppVeyor |
| MSVC 19.16.27035.0 (15.9.21+g9802d43bc3 for .NET Framework) | Windows-10.0.14393 | AppVeyor | | MSVC 19.16.27035.0 (15.9.21+g9802d43bc3 for .NET Framework) | Windows-10.0.14393 | AppVeyor |
| MSVC 19.25.28614.0 (Build Engine version 16.5.0+d4cbfca49 for .NET Framework) | Windows-10.0.17763 | AppVeyor | | MSVC 19.25.28614.0 (Build Engine version 16.5.0+d4cbfca49 for .NET Framework) | Windows-10.0.17763 | AppVeyor |
| MSVC 19.25.28614.0 (Build Engine version 16.5.0+d4cbfca49 for .NET Framework) | Windows-10.0.17763 | GitHub Actions | | MSVC 19.25.28614.0 (Build Engine version 16.5.0+d4cbfca49 for .NET Framework) | Windows-10.0.17763 | GitHub Actions |
| MSVC 19.25.28614.0 (Build Engine version 16.5.0+d4cbfca49 for .NET Framework) with ClangCL 10.0.0 | Windows-10.0.17763 | GitHub Actions |
## License ## License
@ -1163,11 +1275,11 @@ THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR I
* * * * * *
The class contains the UTF-8 Decoder from Bjoern Hoehrmann which is licensed under the [MIT License](http://opensource.org/licenses/MIT) (see above). Copyright &copy; 2008-2009 [Björn Hoehrmann](http://bjoern.hoehrmann.de/) <bjoern@hoehrmann.de> The class contains the UTF-8 Decoder from Bjoern Hoehrmann which is licensed under the [MIT License](http://opensource.org/licenses/MIT) (see above). Copyright &copy; 2008-2009 [Björn Hoehrmann](https://bjoern.hoehrmann.de/) <bjoern@hoehrmann.de>
The class contains a slightly modified version of the Grisu2 algorithm from Florian Loitsch which is licensed under the [MIT License](http://opensource.org/licenses/MIT) (see above). Copyright &copy; 2009 [Florian Loitsch](http://florian.loitsch.com/) The class contains a slightly modified version of the Grisu2 algorithm from Florian Loitsch which is licensed under the [MIT License](http://opensource.org/licenses/MIT) (see above). Copyright &copy; 2009 [Florian Loitsch](https://florian.loitsch.com/)
The class contains a copy of [Hedley](https://nemequ.github.io/hedley/) from Evan Nemerson which is licensed as [CC0-1.0](http://creativecommons.org/publicdomain/zero/1.0/). The class contains a copy of [Hedley](https://nemequ.github.io/hedley/) from Evan Nemerson which is licensed as [CC0-1.0](https://creativecommons.org/publicdomain/zero/1.0/).
## Contact ## Contact
@ -1224,7 +1336,7 @@ I deeply appreciate the help of the following people.
- [Mário Feroldi](https://github.com/thelostt) fixed a small typo. - [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. - [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. - [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. - [Thomas Braun](https://github.com/t-b) fixed a warning in a test case and adjusted MSVC calls in the CI.
- [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). He also implemented the magic behind the serialization/deserialization of user-defined types and split the single header file into smaller chunks. - [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). He also implemented the magic behind the serialization/deserialization of user-defined types and split the single header file into smaller chunks.
- [Stefan](https://github.com/5tefan) fixed a minor issue in the documentation. - [Stefan](https://github.com/5tefan) fixed a minor issue in the documentation.
- [Vasil Dimov](https://github.com/vasild) fixed the documentation regarding conversions from `std::multiset`. - [Vasil Dimov](https://github.com/vasild) fixed the documentation regarding conversions from `std::multiset`.
@ -1368,6 +1480,48 @@ I deeply appreciate the help of the following people.
- [Florian Pigorsch](https://github.com/flopp) fixed a lot of typos. - [Florian Pigorsch](https://github.com/flopp) fixed a lot of typos.
- [Camille Bégué](https://github.com/cbegue) fixed an issue in the conversion from `std::pair` and `std::tuple` to `json`. - [Camille Bégué](https://github.com/cbegue) fixed an issue in the conversion from `std::pair` and `std::tuple` to `json`.
- [Anthony VH](https://github.com/AnthonyVH) fixed a compile error in an enum deserialization. - [Anthony VH](https://github.com/AnthonyVH) fixed a compile error in an enum deserialization.
- [Yuriy Vountesmery](https://github.com/ua-code-dragon) noted a subtle bug in a preprocessor check.
- [Chen](https://github.com/dota17) fixed numerous issues in the library.
- [Antony Kellermann](https://github.com/aokellermann) added a CI step for GCC 10.1.
- [Alex](https://github.com/gistrec) fixed an MSVC warning.
- [Rainer](https://github.com/rvjr) proposed an improvement in the floating-point serialization in CBOR.
- [Francois Chabot](https://github.com/FrancoisChabot) made performance improvements in the input adapters.
- [Arthur Sonzogni](https://github.com/ArthurSonzogni) documented how the library can be included via `FetchContent`.
- [Rimas Misevičius](https://github.com/rmisev) fixed an error message.
- [Alexander Myasnikov](https://github.com/alexandermyasnikov) fixed some examples and a link in the README.
- [Hubert Chathi](https://github.com/uhoreg) made CMake's version config file architecture-independent.
- [OmnipotentEntity](https://github.com/OmnipotentEntity) implemented the binary values for CBOR, MessagePack, BSON, and UBJSON.
- [ArtemSarmini](https://github.com/ArtemSarmini) fixed a compilation issue with GCC 10 and fixed a leak.
- [Evgenii Sopov](https://github.com/sea-kg) integrated the library to the wsjcpp package manager.
- [Sergey Linev](https://github.com/linev) fixed a compiler warning.
- [Miguel Magalhães](https://github.com/magamig) fixed the year in the copyright.
- [Gareth Sylvester-Bradley](https://github.com/garethsb-sony) fixed a compilation issue with MSVC.
- [Alexander “weej” Jones](https://github.com/alex-weej) fixed an example in the README.
- [Antoine Cœur](https://github.com/Coeur) fixed some typos in the documentation.
- [jothepro](https://github.com/jothepro) updated links to the Hunter package.
- [Dave Lee](https://github.com/kastiglione) fixed link in the README.
- [Joël Lamotte](https://github.com/Klaim) added instruction for using Build2's package manager.
- [Paul Jurczak](https://github.com/pauljurczak) fixed an example in the README.
- [Sonu Lohani](https://github.com/sonulohani) fixed a warning.
- [Carlos Gomes Martinho](https://github.com/gocarlos) updated the Conan package source.
- [Konstantin Podsvirov](https://github.com/podsvirov) fixed the MSYS2 package documentation.
- [Tridacnid](https://github.com/Tridacnid) improved the CMake tests.
- [Michael](https://github.com/MBalszun) fixed MSVC warnings.
- [Quentin Barbarat](https://github.com/quentin-dev) fixed an example in the documentation.
- [XyFreak](https://github.com/XyFreak) fixed a compiler warning.
- [TotalCaesar659](https://github.com/TotalCaesar659) fixed links in the README.
- [Tanuj Garg](https://github.com/tanuj208) improved the fuzzer coverage for UBSAN input.
- [AODQ](https://github.com/AODQ) fixed a compiler warning.
- [jwittbrodt](https://github.com/jwittbrodt) made `NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE` inline.
- [pfeatherstone](https://github.com/pfeatherstone) improved the upper bound of arguments of the `NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE`/`NLOHMANN_DEFINE_TYPE_INTRUSIVE` macros.
- [Jan Procházka](https://github.com/jprochazk) fixed a bug in the CBOR parser for binary and string values.
- [T0b1-iOS](https://github.com/T0b1-iOS) fixed a bug in the new hash implementation.
- [Matthew Bauer](https://github.com/matthewbauer) adjusted the CBOR writer to create tags for binary subtypes.
- [gatopeich](https://github.com/gatopeich) implemented an ordered map container for `nlohmann::ordered_json`.
- [Érico Nogueira Rolim](https://github.com/ericonr) added support for pkg-config.
- [KonanM](https://github.com/KonanM) proposed an implementation for the `NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE`/`NLOHMANN_DEFINE_TYPE_INTRUSIVE` macros.
- [Guillaume Racicot](https://github.com/gracicot) implemented `string_view` support and allowed C++20 support.
- [Alex Reinking](https://github.com/alexreinking) improved CMake support for `FetchContent`.
Thanks a lot for helping out! Please [let me know](mailto:mail@nlohmann.me) if I forgot someone. Thanks a lot for helping out! Please [let me know](mailto:mail@nlohmann.me) if I forgot someone.
@ -1377,10 +1531,10 @@ Thanks a lot for helping out! Please [let me know](mailto:mail@nlohmann.me) if I
The library itself consists of a single header file licensed under the MIT license. However, it is built, tested, documented, and whatnot using a lot of third-party tools and services. Thanks a lot! The library itself consists of a single header file licensed under the MIT license. However, it is built, tested, documented, and whatnot using a lot of third-party tools and services. Thanks a lot!
- [**amalgamate.py - Amalgamate C source and header files**](https://github.com/edlund/amalgamate) to create a single header file - [**amalgamate.py - Amalgamate C source and header files**](https://github.com/edlund/amalgamate) to create a single header file
- [**American fuzzy lop**](http://lcamtuf.coredump.cx/afl/) for fuzz testing - [**American fuzzy lop**](https://lcamtuf.coredump.cx/afl/) for fuzz testing
- [**AppVeyor**](https://www.appveyor.com) for [continuous integration](https://ci.appveyor.com/project/nlohmann/json) on Windows - [**AppVeyor**](https://www.appveyor.com) for [continuous integration](https://ci.appveyor.com/project/nlohmann/json) on Windows
- [**Artistic Style**](http://astyle.sourceforge.net) for automatic source code indentation - [**Artistic Style**](http://astyle.sourceforge.net) for automatic source code indentation
- [**CircleCI**](http://circleci.com) for [continuous integration](https://circleci.com/gh/nlohmann/json). - [**CircleCI**](https://circleci.com) for [continuous integration](https://circleci.com/gh/nlohmann/json).
- [**Clang**](https://clang.llvm.org) for compilation with code sanitizers - [**Clang**](https://clang.llvm.org) for compilation with code sanitizers
- [**CMake**](https://cmake.org) for build automation - [**CMake**](https://cmake.org) for build automation
- [**Codacity**](https://www.codacy.com) for further [code analysis](https://www.codacy.com/app/nlohmann/json) - [**Codacity**](https://www.codacy.com) for further [code analysis](https://www.codacy.com/app/nlohmann/json)
@ -1388,19 +1542,19 @@ The library itself consists of a single header file licensed under the MIT licen
- [**Coverity Scan**](https://scan.coverity.com) for [static analysis](https://scan.coverity.com/projects/nlohmann-json) - [**Coverity Scan**](https://scan.coverity.com) for [static analysis](https://scan.coverity.com/projects/nlohmann-json)
- [**cppcheck**](http://cppcheck.sourceforge.net) for static analysis - [**cppcheck**](http://cppcheck.sourceforge.net) for static analysis
- [**doctest**](https://github.com/onqtam/doctest) for the unit tests - [**doctest**](https://github.com/onqtam/doctest) for the unit tests
- [**Doxygen**](http://www.stack.nl/~dimitri/doxygen/) to generate [documentation](https://nlohmann.github.io/json/) - [**Doxygen**](https://www.doxygen.nl/index.html) to generate [documentation](https://nlohmann.github.io/json/doxygen/index.html)
- [**git-update-ghpages**](https://github.com/rstacruz/git-update-ghpages) to upload the documentation to gh-pages - [**git-update-ghpages**](https://github.com/rstacruz/git-update-ghpages) to upload the documentation to gh-pages
- [**GitHub Changelog Generator**](https://github.com/skywinder/github-changelog-generator) to generate the [ChangeLog](https://github.com/nlohmann/json/blob/develop/ChangeLog.md) - [**GitHub Changelog Generator**](https://github.com/skywinder/github-changelog-generator) to generate the [ChangeLog](https://github.com/nlohmann/json/blob/develop/ChangeLog.md)
- [**Google Benchmark**](https://github.com/google/benchmark) to implement the benchmarks - [**Google Benchmark**](https://github.com/google/benchmark) to implement the benchmarks
- [**Hedley**](https://nemequ.github.io/hedley/) to avoid re-inventing several compiler-agnostic feature macros - [**Hedley**](https://nemequ.github.io/hedley/) to avoid re-inventing several compiler-agnostic feature macros
- [**lcov**](http://ltp.sourceforge.net/coverage/lcov.php) to process coverage information and create a HTML view - [**lcov**](http://ltp.sourceforge.net/coverage/lcov.php) to process coverage information and create a HTML view
- [**libFuzzer**](http://llvm.org/docs/LibFuzzer.html) to implement fuzz testing for OSS-Fuzz - [**libFuzzer**](https://llvm.org/docs/LibFuzzer.html) to implement fuzz testing for OSS-Fuzz
- [**OSS-Fuzz**](https://github.com/google/oss-fuzz) for continuous fuzz testing of the library ([project repository](https://github.com/google/oss-fuzz/tree/master/projects/json)) - [**OSS-Fuzz**](https://github.com/google/oss-fuzz) for continuous fuzz testing of the library ([project repository](https://github.com/google/oss-fuzz/tree/master/projects/json))
- [**Probot**](https://probot.github.io) for automating maintainer tasks such as closing stale issues, requesting missing information, or detecting toxic comments. - [**Probot**](https://probot.github.io) for automating maintainer tasks such as closing stale issues, requesting missing information, or detecting toxic comments.
- [**send_to_wandbox**](https://github.com/nlohmann/json/blob/develop/doc/scripts/send_to_wandbox.py) to send code examples to [Wandbox](http://melpon.org/wandbox) - [**send_to_wandbox**](https://github.com/nlohmann/json/blob/develop/doc/scripts/send_to_wandbox.py) to send code examples to [Wandbox](http://melpon.org/wandbox)
- [**Travis**](https://travis-ci.org) for [continuous integration](https://travis-ci.org/nlohmann/json) on Linux and macOS - [**Travis**](https://travis-ci.org) for [continuous integration](https://travis-ci.org/nlohmann/json) on Linux and macOS
- [**Valgrind**](http://valgrind.org) to check for correct memory management - [**Valgrind**](https://valgrind.org) to check for correct memory management
- [**Wandbox**](http://melpon.org/wandbox) for [online examples](https://wandbox.org/permlink/3lCHrFUZANONKv7a) - [**Wandbox**](https://wandbox.org) for [online examples](https://wandbox.org/permlink/3lCHrFUZANONKv7a)
## Projects using JSON for Modern C++ ## Projects using JSON for Modern C++
@ -1417,14 +1571,14 @@ The library supports **Unicode input** as follows:
- Only **UTF-8** encoded input is supported which is the default encoding for JSON according to [RFC 8259](https://tools.ietf.org/html/rfc8259.html#section-8.1). - Only **UTF-8** encoded input is supported which is the default encoding for JSON according to [RFC 8259](https://tools.ietf.org/html/rfc8259.html#section-8.1).
- `std::u16string` and `std::u32string` can be parsed, assuming UTF-16 and UTF-32 encoding, respectively. These encodings are not supported when reading from files or other input containers. - `std::u16string` and `std::u32string` can be parsed, assuming UTF-16 and UTF-32 encoding, respectively. These encodings are not supported when reading from files or other input containers.
- Other encodings such as Latin-1 or ISO 8859-1 are **not** supported and will yield parse or serialization errors. - Other encodings such as Latin-1 or ISO 8859-1 are **not** supported and will yield parse or serialization errors.
- [Unicode noncharacters](http://www.unicode.org/faq/private_use.html#nonchar1) will not be replaced by the library. - [Unicode noncharacters](https://www.unicode.org/faq/private_use.html#nonchar1) will not be replaced by the library.
- Invalid surrogates (e.g., incomplete pairs such as `\uDEAD`) will yield parse errors. - Invalid surrogates (e.g., incomplete pairs such as `\uDEAD`) will yield parse errors.
- The strings stored in the library are UTF-8 encoded. When using the default string type (`std::string`), note that its length/size functions return the number of stored bytes rather than the number of characters or glyphs. - The strings stored in the library are UTF-8 encoded. When using the default string type (`std::string`), note that its length/size functions return the number of stored bytes rather than the number of characters or glyphs.
- When you store strings with different encodings in the library, calling [`dump()`](https://nlohmann.github.io/json/classnlohmann_1_1basic__json_a50ec80b02d0f3f51130d4abb5d1cfdc5.html#a50ec80b02d0f3f51130d4abb5d1cfdc5) may throw an exception unless `json::error_handler_t::replace` or `json::error_handler_t::ignore` are used as error handlers. - When you store strings with different encodings in the library, calling [`dump()`](https://nlohmann.github.io/json/classnlohmann_1_1basic__json_a50ec80b02d0f3f51130d4abb5d1cfdc5.html#a50ec80b02d0f3f51130d4abb5d1cfdc5) may throw an exception unless `json::error_handler_t::replace` or `json::error_handler_t::ignore` are used as error handlers.
### Comments in JSON ### Comments in JSON
This library does not support comments. It does so for three reasons: This library does not support comments by default. It does so for three reasons:
1. Comments are not part of the [JSON specification](https://tools.ietf.org/html/rfc8259). You may argue that `//` or `/* */` are allowed in JavaScript, but JSON is not JavaScript. 1. Comments are not part of the [JSON specification](https://tools.ietf.org/html/rfc8259). You may argue that `//` or `/* */` are allowed in JavaScript, but JSON is not JavaScript.
2. This was not an oversight: Douglas Crockford [wrote on this](https://plus.google.com/118095276221607585885/posts/RK8qyGVaGSr) in May 2012: 2. This was not an oversight: Douglas Crockford [wrote on this](https://plus.google.com/118095276221607585885/posts/RK8qyGVaGSr) in May 2012:
@ -1435,15 +1589,13 @@ This library does not support comments. It does so for three reasons:
3. It is dangerous for interoperability if some libraries would add comment support while others don't. Please check [The Harmful Consequences of the Robustness Principle](https://tools.ietf.org/html/draft-iab-protocol-maintenance-01) on this. 3. It is dangerous for interoperability if some libraries would add comment support while others don't. Please check [The Harmful Consequences of the Robustness Principle](https://tools.ietf.org/html/draft-iab-protocol-maintenance-01) on this.
This library will not support comments in the future. If you wish to use comments, I see three options: However, you can pass set parameter `ignore_comments` to true in the `parse` function to ignore `//` or `/* */` comments. Comments will then be treated as whitespace.
1. Strip comments before using this library.
2. Use a different JSON library with comment support.
3. Use a format that natively supports comments (e.g., YAML or JSON5).
### Order of object keys ### Order of object keys
By default, the library does not preserve the **insertion order of object elements**. This is standards-compliant, as the [JSON standard](https://tools.ietf.org/html/rfc8259.html) defines objects as "an unordered collection of zero or more name/value pairs". If you do want to preserve the insertion order, you can specialize the object type with containers like [`tsl::ordered_map`](https://github.com/Tessil/ordered-map) ([integration](https://github.com/nlohmann/json/issues/546#issuecomment-304447518)) or [`nlohmann::fifo_map`](https://github.com/nlohmann/fifo_map) ([integration](https://github.com/nlohmann/json/issues/485#issuecomment-333652309)). By default, the library does not preserve the **insertion order of object elements**. This is standards-compliant, as the [JSON standard](https://tools.ietf.org/html/rfc8259.html) defines objects as "an unordered collection of zero or more name/value pairs".
If you do want to preserve the insertion order, you can try the type [`nlohmann::ordered_json`](https://github.com/nlohmann/json/issues/2179). Alternatively, you can use a more sophisticated ordered map like [`tsl::ordered_map`](https://github.com/Tessil/ordered-map) ([integration](https://github.com/nlohmann/json/issues/546#issuecomment-304447518)) or [`nlohmann::fifo_map`](https://github.com/nlohmann/fifo_map) ([integration](https://github.com/nlohmann/json/issues/485#issuecomment-333652309)).
### Memory Release ### Memory Release
@ -1456,10 +1608,10 @@ Here is a related issue [#1924](https://github.com/nlohmann/json/issues/1924).
### Further notes ### Further notes
- The code contains numerous debug **assertions** which can be switched off by defining the preprocessor macro `NDEBUG`, see the [documentation of `assert`](https://en.cppreference.com/w/cpp/error/assert). In particular, note [`operator[]`](https://nlohmann.github.io/json/classnlohmann_1_1basic__json_a233b02b0839ef798942dd46157cc0fe6.html#a233b02b0839ef798942dd46157cc0fe6) 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_a73ae333487310e3302135189ce8ff5d8.html#a73ae333487310e3302135189ce8ff5d8). - The code contains numerous debug **assertions** which can be switched off by defining the preprocessor macro `NDEBUG`, see the [documentation of `assert`](https://en.cppreference.com/w/cpp/error/assert). In particular, note [`operator[]`](https://nlohmann.github.io/json/classnlohmann_1_1basic__json_a233b02b0839ef798942dd46157cc0fe6.html#a233b02b0839ef798942dd46157cc0fe6) 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_a73ae333487310e3302135189ce8ff5d8.html#a73ae333487310e3302135189ce8ff5d8). Furthermore, you can define `JSON_ASSERT(x)` to replace calls to `assert(x)`.
- As the exact type of a number is not defined in the [JSON specification](https://tools.ietf.org/html/rfc8259.html), 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. - As the exact type of a number is not defined in the [JSON specification](https://tools.ietf.org/html/rfc8259.html), 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.
- The code can be compiled without C++ **runtime type identification** features; that is, you can use the `-fno-rtti` compiler flag. - The code can be compiled without C++ **runtime type identification** features; that is, you can use the `-fno-rtti` compiler flag.
- **Exceptions** are used widely within the library. They can, however, be switched off with either using the compiler flag `-fno-exceptions` or by defining the symbol `JSON_NOEXCEPTION`. In this case, exceptions are replaced by `abort()` calls. You can further control this behavior by defining `JSON_THROW_USER´` (overriding `throw`), `JSON_TRY_USER` (overriding `try`), and `JSON_CATCH_USER` (overriding `catch`). Note that `JSON_THROW_USER` should leave the current scope (e.g., by throwing or aborting), as continuing after it may yield undefined behavior. - **Exceptions** are used widely within the library. They can, however, be switched off with either using the compiler flag `-fno-exceptions` or by defining the symbol `JSON_NOEXCEPTION`. In this case, exceptions are replaced by `abort()` calls. You can further control this behavior by defining `JSON_THROW_USER` (overriding `throw`), `JSON_TRY_USER` (overriding `try`), and `JSON_CATCH_USER` (overriding `catch`). Note that `JSON_THROW_USER` should leave the current scope (e.g., by throwing or aborting), as continuing after it may yield undefined behavior.
## Execute unit tests ## Execute unit tests
@ -1468,9 +1620,11 @@ To compile and run the tests, you need to execute
```sh ```sh
$ mkdir build $ mkdir build
$ cd build $ cd build
$ cmake .. $ cmake .. -DJSON_BuildTests=On
$ cmake --build . $ cmake --build .
$ ctest --output-on-failure $ ctest --output-on-failure
``` ```
For more information, have a look at the file [.travis.yml](https://github.com/nlohmann/json/blob/master/.travis.yml). Note that during the `ctest` stage, several JSON test files are downloaded from an [external repository](https://github.com/nlohmann/json_test_data). If policies forbid downloading artifacts during testing, you can download the files yourself and pass the directory with the test files via `-DJSON_TestDataDirectory=path` to CMake. Then, no Internet connectivity is required. See [issue #2189](https://github.com/nlohmann/json/issues/2189) for more information.
In case you have downloaded the library rather than checked out the code via Git, test `cmake_fetch_content_configure`. Please execute `ctest -LE git_required` to skip these tests. See [issue #2189](https://github.com/nlohmann/json/issues/2189) for more information.

View File

@ -7,6 +7,7 @@ environment:
platform: x86 platform: x86
CXX_FLAGS: "" CXX_FLAGS: ""
LINKER_FLAGS: "" LINKER_FLAGS: ""
CMAKE_OPTIONS: ""
GENERATOR: Visual Studio 14 2015 GENERATOR: Visual Studio 14 2015
- APPVEYOR_BUILD_WORKER_IMAGE: Visual Studio 2017 - APPVEYOR_BUILD_WORKER_IMAGE: Visual Studio 2017
@ -14,6 +15,7 @@ environment:
platform: x86 platform: x86
CXX_FLAGS: "" CXX_FLAGS: ""
LINKER_FLAGS: "" LINKER_FLAGS: ""
CMAKE_OPTIONS: ""
GENERATOR: Visual Studio 15 2017 GENERATOR: Visual Studio 15 2017
- APPVEYOR_BUILD_WORKER_IMAGE: Visual Studio 2019 - APPVEYOR_BUILD_WORKER_IMAGE: Visual Studio 2019
@ -21,6 +23,7 @@ environment:
platform: x86 platform: x86
CXX_FLAGS: "" CXX_FLAGS: ""
LINKER_FLAGS: "" LINKER_FLAGS: ""
CMAKE_OPTIONS: ""
GENERATOR: Visual Studio 16 2019 GENERATOR: Visual Studio 16 2019
- APPVEYOR_BUILD_WORKER_IMAGE: Visual Studio 2019 - APPVEYOR_BUILD_WORKER_IMAGE: Visual Studio 2019
@ -28,6 +31,7 @@ environment:
platform: x64 platform: x64
CXX_FLAGS: "" CXX_FLAGS: ""
LINKER_FLAGS: "" LINKER_FLAGS: ""
CMAKE_OPTIONS: ""
GENERATOR: Visual Studio 16 2019 GENERATOR: Visual Studio 16 2019
- APPVEYOR_BUILD_WORKER_IMAGE: Visual Studio 2015 - APPVEYOR_BUILD_WORKER_IMAGE: Visual Studio 2015
@ -36,6 +40,7 @@ environment:
platform: x86 platform: x86
CXX_FLAGS: "" CXX_FLAGS: ""
LINKER_FLAGS: "" LINKER_FLAGS: ""
CMAKE_OPTIONS: ""
GENERATOR: Ninja GENERATOR: Ninja
- APPVEYOR_BUILD_WORKER_IMAGE: Visual Studio 2015 - APPVEYOR_BUILD_WORKER_IMAGE: Visual Studio 2015
@ -44,6 +49,7 @@ environment:
platform: x86 platform: x86
CXX_FLAGS: "" CXX_FLAGS: ""
LINKER_FLAGS: "" LINKER_FLAGS: ""
CMAKE_OPTIONS: ""
GENERATOR: Ninja GENERATOR: Ninja
- APPVEYOR_BUILD_WORKER_IMAGE: Visual Studio 2015 - APPVEYOR_BUILD_WORKER_IMAGE: Visual Studio 2015
@ -51,6 +57,7 @@ environment:
platform: x86 platform: x86
CXX_FLAGS: "" CXX_FLAGS: ""
LINKER_FLAGS: "" LINKER_FLAGS: ""
CMAKE_OPTIONS: ""
GENERATOR: Visual Studio 14 2015 GENERATOR: Visual Studio 14 2015
- APPVEYOR_BUILD_WORKER_IMAGE: Visual Studio 2015 - APPVEYOR_BUILD_WORKER_IMAGE: Visual Studio 2015
@ -59,6 +66,7 @@ environment:
name: with_win_header name: with_win_header
CXX_FLAGS: "" CXX_FLAGS: ""
LINKER_FLAGS: "" LINKER_FLAGS: ""
CMAKE_OPTIONS: ""
GENERATOR: Visual Studio 14 2015 GENERATOR: Visual Studio 14 2015
- APPVEYOR_BUILD_WORKER_IMAGE: Visual Studio 2017 - APPVEYOR_BUILD_WORKER_IMAGE: Visual Studio 2017
@ -66,6 +74,7 @@ environment:
platform: x86 platform: x86
CXX_FLAGS: "/permissive- /std:c++latest /utf-8" CXX_FLAGS: "/permissive- /std:c++latest /utf-8"
LINKER_FLAGS: "" LINKER_FLAGS: ""
CMAKE_OPTIONS: ""
GENERATOR: Visual Studio 15 2017 GENERATOR: Visual Studio 15 2017
- APPVEYOR_BUILD_WORKER_IMAGE: Visual Studio 2019 - APPVEYOR_BUILD_WORKER_IMAGE: Visual Studio 2019
@ -73,6 +82,15 @@ environment:
platform: x86 platform: x86
CXX_FLAGS: "" CXX_FLAGS: ""
LINKER_FLAGS: "" LINKER_FLAGS: ""
CMAKE_OPTIONS: "-DJSON_ImplicitConversions=OFF"
GENERATOR: Visual Studio 16 2019
- APPVEYOR_BUILD_WORKER_IMAGE: Visual Studio 2019
configuration: Release
platform: x64
CXX_FLAGS: ""
LINKER_FLAGS: ""
CMAKE_OPTIONS: ""
GENERATOR: Visual Studio 16 2019 GENERATOR: Visual Studio 16 2019
- APPVEYOR_BUILD_WORKER_IMAGE: Visual Studio 2015 - APPVEYOR_BUILD_WORKER_IMAGE: Visual Studio 2015
@ -80,6 +98,7 @@ environment:
platform: x64 platform: x64
CXX_FLAGS: "" CXX_FLAGS: ""
LINKER_FLAGS: "" LINKER_FLAGS: ""
CMAKE_OPTIONS: ""
GENERATOR: Visual Studio 14 2015 GENERATOR: Visual Studio 14 2015
- APPVEYOR_BUILD_WORKER_IMAGE: Visual Studio 2017 - APPVEYOR_BUILD_WORKER_IMAGE: Visual Studio 2017
@ -87,6 +106,7 @@ environment:
platform: x64 platform: x64
CXX_FLAGS: "/permissive- /std:c++latest /Zc:__cplusplus /utf-8 /F4000000" CXX_FLAGS: "/permissive- /std:c++latest /Zc:__cplusplus /utf-8 /F4000000"
LINKER_FLAGS: "/STACK:4000000" LINKER_FLAGS: "/STACK:4000000"
CMAKE_OPTIONS: ""
GENERATOR: Visual Studio 15 2017 GENERATOR: Visual Studio 15 2017
- APPVEYOR_BUILD_WORKER_IMAGE: Visual Studio 2019 - APPVEYOR_BUILD_WORKER_IMAGE: Visual Studio 2019
@ -94,6 +114,7 @@ environment:
platform: x64 platform: x64
CXX_FLAGS: "" CXX_FLAGS: ""
LINKER_FLAGS: "" LINKER_FLAGS: ""
CMAKE_OPTIONS: ""
GENERATOR: Visual Studio 16 2019 GENERATOR: Visual Studio 16 2019
init: init:
@ -112,7 +133,7 @@ before_build:
# for with_win_header build, inject the inclusion of Windows.h to the single-header library # for with_win_header build, inject the inclusion of Windows.h to the single-header library
- ps: if ($env:name -Eq "with_win_header") { $header_path = "single_include\nlohmann\json.hpp" } - ps: if ($env:name -Eq "with_win_header") { $header_path = "single_include\nlohmann\json.hpp" }
- ps: if ($env:name -Eq "with_win_header") { "#include <Windows.h>`n" + (Get-Content $header_path | Out-String) | Set-Content $header_path } - ps: if ($env:name -Eq "with_win_header") { "#include <Windows.h>`n" + (Get-Content $header_path | Out-String) | Set-Content $header_path }
- if "%GENERATOR%"=="Ninja" (cmake . -G "%GENERATOR%" -DCMAKE_BUILD_TYPE="%configuration%" -DCMAKE_CXX_FLAGS="%CXX_FLAGS%" -DCMAKE_EXE_LINKER_FLAGS="%LINKER_FLAGS%" -DCMAKE_IGNORE_PATH="C:/Program Files/Git/usr/bin") else (cmake . -G "%GENERATOR%" -A "%GENERATOR_PLATFORM%" -DCMAKE_CXX_FLAGS="%CXX_FLAGS%" -DCMAKE_EXE_LINKER_FLAGS="%LINKER_FLAGS%" -DCMAKE_IGNORE_PATH="C:/Program Files/Git/usr/bin") - if "%GENERATOR%"=="Ninja" (cmake . -G "%GENERATOR%" -DCMAKE_BUILD_TYPE="%configuration%" -DCMAKE_CXX_FLAGS="%CXX_FLAGS%" -DCMAKE_EXE_LINKER_FLAGS="%LINKER_FLAGS%" -DCMAKE_IGNORE_PATH="C:/Program Files/Git/usr/bin" -DJSON_BuildTests=On "%CMAKE_OPTIONS%") else (cmake . -G "%GENERATOR%" -A "%GENERATOR_PLATFORM%" -DCMAKE_CXX_FLAGS="%CXX_FLAGS%" -DCMAKE_EXE_LINKER_FLAGS="%LINKER_FLAGS%" -DCMAKE_IGNORE_PATH="C:/Program Files/Git/usr/bin" -DJSON_BuildTests=On "%CMAKE_OPTIONS%")
build_script: build_script:
- cmake --build . --config "%configuration%" - cmake --build . --config "%configuration%"

View File

@ -1,17 +1,22 @@
find_package(Git)
set(JSON_TEST_DATA_URL https://github.com/nlohmann/json_test_data) set(JSON_TEST_DATA_URL https://github.com/nlohmann/json_test_data)
set(JSON_TEST_DATA_VERSION 2.0.0) set(JSON_TEST_DATA_VERSION 3.0.0)
# target to download test data # if variable is set, use test data from given directory rather than downloading them
add_custom_target(download_test_data if(JSON_TestDataDirectory)
message(STATUS "Using test data in ${JSON_TestDataDirectory}.")
add_custom_target(download_test_data)
file(WRITE ${CMAKE_BINARY_DIR}/include/test_data.hpp "#define TEST_DATA_DIRECTORY \"${JSON_TestDataDirectory}\"\n")
else()
find_package(Git)
# target to download test data
add_custom_target(download_test_data
COMMAND test -d json_test_data || ${GIT_EXECUTABLE} clone -c advice.detachedHead=false --branch v${JSON_TEST_DATA_VERSION} ${JSON_TEST_DATA_URL}.git --quiet --depth 1 COMMAND test -d json_test_data || ${GIT_EXECUTABLE} clone -c advice.detachedHead=false --branch v${JSON_TEST_DATA_VERSION} ${JSON_TEST_DATA_URL}.git --quiet --depth 1
COMMENT "Downloading test data from ${JSON_TEST_DATA_URL} (v${JSON_TEST_DATA_VERSION})" COMMENT "Downloading test data from ${JSON_TEST_DATA_URL} (v${JSON_TEST_DATA_VERSION})"
WORKING_DIRECTORY ${CMAKE_BINARY_DIR} WORKING_DIRECTORY ${CMAKE_BINARY_DIR}
) )
# create a header with the path to the downloaded test data
# create a header with the path to the downloaded test data file(WRITE ${CMAKE_BINARY_DIR}/include/test_data.hpp "#define TEST_DATA_DIRECTORY \"${CMAKE_BINARY_DIR}/json_test_data\"\n")
file(WRITE ${CMAKE_BINARY_DIR}/include/test_data.hpp "#define TEST_DATA_DIRECTORY \"${CMAKE_BINARY_DIR}/json_test_data\"\n") endif()
# determine the operating system (for debug and support purposes) # determine the operating system (for debug and support purposes)
find_program(UNAME_COMMAND uname) find_program(UNAME_COMMAND uname)

4
cmake/pkg-config.pc.in Normal file
View File

@ -0,0 +1,4 @@
Name: ${PROJECT_NAME}
Description: JSON for Modern C++
Version: ${PROJECT_VERSION}
Cflags: -I${CMAKE_INSTALL_PREFIX}/${CMAKE_INSTALL_INCLUDEDIR}

View File

@ -5,7 +5,7 @@
#--------------------------------------------------------------------------- #---------------------------------------------------------------------------
DOXYFILE_ENCODING = UTF-8 DOXYFILE_ENCODING = UTF-8
PROJECT_NAME = "JSON for Modern C++" PROJECT_NAME = "JSON for Modern C++"
PROJECT_NUMBER = 3.7.3 PROJECT_NUMBER = 3.9.1
PROJECT_BRIEF = PROJECT_BRIEF =
PROJECT_LOGO = PROJECT_LOGO =
OUTPUT_DIRECTORY = . OUTPUT_DIRECTORY = .
@ -110,9 +110,7 @@ WARN_LOGFILE =
# Configuration options related to the input files # Configuration options related to the input files
#--------------------------------------------------------------------------- #---------------------------------------------------------------------------
INPUT = ../single_include/nlohmann/json.hpp \ INPUT = ../single_include/nlohmann/json.hpp \
index.md \ index.md
faq.md \
binary_formats.md
INPUT_ENCODING = UTF-8 INPUT_ENCODING = UTF-8
FILE_PATTERNS = FILE_PATTERNS =
RECURSIVE = NO RECURSIVE = NO

View File

@ -43,7 +43,7 @@ check_output: $(EXAMPLES:.cpp=.test)
clean: clean:
rm -fr me.nlohmann.json.docset html $(EXAMPLES:.cpp=) rm -fr me.nlohmann.json.docset html xml $(EXAMPLES:.cpp=)
########################################################################## ##########################################################################

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.0 MiB

After

Width:  |  Height:  |  Size: 1.1 MiB

View File

@ -1,171 +0,0 @@
# Binary formats
![conversion between JSON and binary formats](images/binary.png)
Several formats exist that encode JSON values in a binary format to reduce the size of the encoded value as well as the required effort to parse encoded value. The library implements three formats, namely
- [CBOR](https://tools.ietf.org/html/rfc7049) (Concise Binary Object Representation)
- [MessagePack](https://msgpack.org)
- [UBJSON](http://ubjson.org) (Universal Binary JSON)
## Interface
### JSON to binary format
For each format, the `to_*` functions (i.e., `to_cbor`, `to_msgpack`, and `to_ubjson`) convert a JSON value into the respective binary format. Taking CBOR as example, the concrete prototypes are:
```cpp
static std::vector<uint8_t> to_cbor(const basic_json& j); // 1
static void to_cbor(const basic_json& j, detail::output_adapter<uint8_t> o); // 2
static void to_cbor(const basic_json& j, detail::output_adapter<char> o); // 3
```
The first function creates a byte vector from the given JSON value. The second and third function writes to an output adapter of `uint8_t` and `char`, respectively. Output adapters are implemented for strings, output streams, and vectors.
Given a JSON value `j`, the following calls are possible:
```cpp
std::vector<uint8_t> v;
v = json::to_cbor(j); // 1
json::to_cbor(j, v); // 2
std::string s;
json::to_cbor(j, s); // 3
std::ostringstream oss;
json::to_cbor(j, oss); // 3
```
### Binary format to JSON
Likewise, the `from_*` functions (i.e, `from_cbor`, `from_msgpack`, and `from_ubjson`) convert a binary encoded value into a JSON value. Taking CBOR as example, the concrete prototypes are:
```cpp
static basic_json from_cbor(detail::input_adapter i, const bool strict = true); // 1
static basic_json from_cbor(A1 && a1, A2 && a2, const bool strict = true); // 2
```
Both functions read from an input adapter: the first function takes it directly form argument `i`, whereas the second function creates it from the provided arguments `a1` and `a2`. If the optional parameter `strict` is true, the input must be read completely (or a parse error exception is thrown). If it is false, parsing succeeds even if the input is not completely read.
Input adapters are implemented for input streams, character buffers, string literals, and iterator ranges.
Given several inputs (which we assume to be filled with a CBOR value), the following calls are possible:
```cpp
std::string s;
json j1 = json::from_cbor(s); // 1
std::ifstream is("somefile.cbor", std::ios::binary);
json j2 = json::from_cbor(is); // 1
std::vector<uint8_t> v;
json j3 = json::from_cbor(v); // 1
const char* buff;
std::size_t buff_size;
json j4 = json::from_cbor(buff, buff_size); // 2
```
## Details
### CBOR
The mapping from CBOR to JSON is **incomplete** in the sense that not all CBOR types can be converted to a JSON value. The following CBOR types are not supported and will yield parse errors (parse_error.112):
- byte strings (0x40..0x5F)
- date/time (0xC0..0xC1)
- bignum (0xC2..0xC3)
- decimal fraction (0xC4)
- bigfloat (0xC5)
- tagged items (0xC6..0xD4, 0xD8..0xDB)
- expected conversions (0xD5..0xD7)
- simple values (0xE0..0xF3, 0xF8)
- undefined (0xF7)
CBOR further allows map keys of any type, whereas JSON only allows strings as keys in object values. Therefore, CBOR maps with keys other than UTF-8 strings are rejected (parse_error.113).
The mapping from JSON to CBOR is **complete** in the sense that any JSON value type can be converted to a CBOR value.
If NaN or Infinity are stored inside a JSON number, they are serialized properly. This behavior differs from the dump() function which serializes NaN or Infinity to null.
The following CBOR types are not used in the conversion:
- byte strings (0x40..0x5F)
- UTF-8 strings terminated by "break" (0x7F)
- arrays terminated by "break" (0x9F)
- maps terminated by "break" (0xBF)
- date/time (0xC0..0xC1)
- bignum (0xC2..0xC3)
- decimal fraction (0xC4)
- bigfloat (0xC5)
- tagged items (0xC6..0xD4, 0xD8..0xDB)
- expected conversions (0xD5..0xD7)
- simple values (0xE0..0xF3, 0xF8)
- undefined (0xF7)
- half and single-precision floats (0xF9-0xFA)
- break (0xFF)
### MessagePack
The mapping from MessagePack to JSON is **incomplete** in the sense that not all MessagePack types can be converted to a JSON value. The following MessagePack types are not supported and will yield parse errors:
- bin 8 - bin 32 (0xC4..0xC6)
- ext 8 - ext 32 (0xC7..0xC9)
- fixext 1 - fixext 16 (0xD4..0xD8)
The mapping from JSON to MessagePack is **complete** in the sense that any JSON value type can be converted to a MessagePack value.
The following values can not be converted to a MessagePack value:
- strings with more than 4294967295 bytes
- arrays with more than 4294967295 elements
- objects with more than 4294967295 elements
The following MessagePack types are not used in the conversion:
- bin 8 - bin 32 (0xC4..0xC6)
- ext 8 - ext 32 (0xC7..0xC9)
- float 32 (0xCA)
- fixext 1 - fixext 16 (0xD4..0xD8)
Any MessagePack output created `to_msgpack` can be successfully parsed by `from_msgpack`.
If NaN or Infinity are stored inside a JSON number, they are serialized properly. This behavior differs from the `dump()` function which serializes NaN or Infinity to `null`.
### UBJSON
The mapping from UBJSON to JSON is **complete** in the sense that any UBJSON value can be converted to a JSON value.
The mapping from JSON to UBJSON is **complete** in the sense that any JSON value type can be converted to a UBJSON value.
The following values can not be converted to a UBJSON value:
- strings with more than 9223372036854775807 bytes (theoretical)
- unsigned integer numbers above 9223372036854775807
The following markers are not used in the conversion:
- `Z`: no-op values are not created.
- `C`: single-byte strings are serialized with S markers.
Any UBJSON output created to_ubjson can be successfully parsed by from_ubjson.
If NaN or Infinity are stored inside a JSON number, they are serialized properly. This behavior differs from the `dump()` function which serializes NaN or Infinity to null.
The optimized formats for containers are supported: Parameter `use_size` adds size information to the beginning of a container and removes the closing marker. Parameter `use_type` further checks whether all elements of a container have the same type and adds the type marker to the beginning of the container. The `use_type` parameter must only be used together with `use_size = true`. Note that `use_size = true` alone may result in larger representations - the benefit of this parameter is that the receiving side is immediately informed on the number of elements of the container.
## Size comparison examples
The following table shows the size compared to the original JSON value for different files from the repository for the different formats.
| format | sample.json | all_unicode.json | floats.json | signed_ints.json | jeopardy.json | canada.json |
| ----------------------- | -----------:| ----------------:| -----------:| ----------------:| -------------:| -----------:|
| JSON | 100.00 % | 100.00 % | 100.00 % | 100.00 % | 100.00 % | 100.00 % |
| CBOR | 87.21 % | 71.18 % | 48.20 % | 44.16 % | 87.96 % | 50.53 % |
| MessagePack | 87.16 % | 71.18 % | 48.20 % | 44.16 % | 87.91 % | 50.56 % |
| UBJSON unoptimized | 88.15 % | 100.00 % | 48.20 % | 44.16 % | 96.58 % | 53.20 % |
| UBJSON size-optimized | 89.26 % | 100.00 % | 48.20 % | 44.16 % | 97.40 % | 58.56 % |
| UBJSON format-optimized | 89.45 % | 100.00 % | 42.85 % | 39.26 % | 94.96 % | 55.93 % |
The results show that there does not exist a "best" encoding. Furthermore, it is not always worthwhile to use UBJSON's optimizations.

View File

@ -1 +1 @@
<a target="_blank" href="https://wandbox.org/permlink/OX1IUGHx94Dvthnq"><b>online</b></a> <a target="_blank" href="https://wandbox.org/permlink/UYcLkpu1GaaAO2Cp"><b>online</b></a>

View File

@ -0,0 +1,26 @@
#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';
}

View File

@ -0,0 +1 @@
<a target="_blank" href="https://wandbox.org/permlink/r5Tai1spihWHTdFA"><b>online</b></a>

View File

@ -0,0 +1 @@
true false

View File

@ -1 +1 @@
<a target="_blank" href="https://wandbox.org/permlink/piWraYhVg2CV3j2H"><b>online</b></a> <a target="_blank" href="https://wandbox.org/permlink/Ptk2BoNyGfrZfxRU"><b>online</b></a>

View File

@ -1 +1 @@
<a target="_blank" href="https://wandbox.org/permlink/wtWzPSQWWiuxldVs"><b>online</b></a> <a target="_blank" href="https://wandbox.org/permlink/055DW3OWJPwGYr92"><b>online</b></a>

View File

@ -1 +1 @@
<a target="_blank" href="https://wandbox.org/permlink/PjhAXOF8TTuwibn6"><b>online</b></a> <a target="_blank" href="https://wandbox.org/permlink/gM1uqvzukokLwjMa"><b>online</b></a>

View File

@ -1 +1 @@
<a target="_blank" href="https://wandbox.org/permlink/MfM8XIuPWMvxxdeb"><b>online</b></a> <a target="_blank" href="https://wandbox.org/permlink/H3tBOr4lpufGRHlF"><b>online</b></a>

View File

@ -1 +1 @@
<a target="_blank" href="https://wandbox.org/permlink/eFEcnFZxfdLGSMhw"><b>online</b></a> <a target="_blank" href="https://wandbox.org/permlink/UtGhIQGxCYIml36F"><b>online</b></a>

View File

@ -1 +1 @@
<a target="_blank" href="https://wandbox.org/permlink/ST2lraxpPLdDOUFn"><b>online</b></a> <a target="_blank" href="https://wandbox.org/permlink/NHe5FLR1KYaiHwBx"><b>online</b></a>

View File

@ -1 +1 @@
<a target="_blank" href="https://wandbox.org/permlink/FkPwquIlr9pojvGf"><b>online</b></a> <a target="_blank" href="https://wandbox.org/permlink/lbZjdwg6yII33cV5"><b>online</b></a>

View File

@ -1 +1 @@
<a target="_blank" href="https://wandbox.org/permlink/AxHC1Xl6KALWJ0FJ"><b>online</b></a> <a target="_blank" href="https://wandbox.org/permlink/swnzqmd8zj6ij1fb"><b>online</b></a>

View File

@ -1 +1 @@
<a target="_blank" href="https://wandbox.org/permlink/pylFciQUhOx6zXW8"><b>online</b></a> <a target="_blank" href="https://wandbox.org/permlink/RodBcX8vpcP5dQ40"><b>online</b></a>

View File

@ -1 +1 @@
<a target="_blank" href="https://wandbox.org/permlink/KCfRvbW3QTvghlFb"><b>online</b></a> <a target="_blank" href="https://wandbox.org/permlink/oWFo4AhVlMBjNv8E"><b>online</b></a>

View File

@ -1 +1 @@
<a target="_blank" href="https://wandbox.org/permlink/TM0OkdSgEIGBDbrv"><b>online</b></a> <a target="_blank" href="https://wandbox.org/permlink/oRn0YsYyurs0Zi5T"><b>online</b></a>

View File

@ -1 +1 @@
<a target="_blank" href="https://wandbox.org/permlink/jWDJPXw490IFoVL1"><b>online</b></a> <a target="_blank" href="https://wandbox.org/permlink/kVknQzPMpqjywTpG"><b>online</b></a>

View File

@ -1 +1 @@
<a target="_blank" href="https://wandbox.org/permlink/FR2ImEj05R1bqqZ2"><b>online</b></a> <a target="_blank" href="https://wandbox.org/permlink/yzkjGGzMOESBkCdH"><b>online</b></a>

View File

@ -1 +1 @@
<a target="_blank" href="https://wandbox.org/permlink/XTHN0lMT9QsmBcBy"><b>online</b></a> <a target="_blank" href="https://wandbox.org/permlink/eIOvQiuID2qgxp5u"><b>online</b></a>

View File

@ -1 +1 @@
<a target="_blank" href="https://wandbox.org/permlink/iCwvXJinCVY7q1vi"><b>online</b></a> <a target="_blank" href="https://wandbox.org/permlink/Vm0nR32x6co8rq40"><b>online</b></a>

View File

@ -1 +1 @@
<a target="_blank" href="https://wandbox.org/permlink/BzyeWqt4uTQ2nbfx"><b>online</b></a> <a target="_blank" href="https://wandbox.org/permlink/w4TtEQzlVyokIrtp"><b>online</b></a>

View File

@ -1 +1 @@
<a target="_blank" href="https://wandbox.org/permlink/zFWa3Zyot2oM3Z8O"><b>online</b></a> <a target="_blank" href="https://wandbox.org/permlink/mNy1nyabOkeHfHGf"><b>online</b></a>

View File

@ -1 +1 @@
<a target="_blank" href="https://wandbox.org/permlink/ECfvMr4m68Mfr192"><b>online</b></a> <a target="_blank" href="https://wandbox.org/permlink/a3H6kpORXgbVXylv"><b>online</b></a>

View File

@ -1 +1 @@
<a target="_blank" href="https://wandbox.org/permlink/LNck7Gktm14bmPy0"><b>online</b></a> <a target="_blank" href="https://wandbox.org/permlink/yXZGDwDHH3LOuFIr"><b>online</b></a>

View File

@ -1 +1 @@
<a target="_blank" href="https://wandbox.org/permlink/I1e2Y91igQv2vxbo"><b>online</b></a> <a target="_blank" href="https://wandbox.org/permlink/fS4kfQG1hmhjMScn"><b>online</b></a>

View File

@ -1 +1 @@
<a target="_blank" href="https://wandbox.org/permlink/tGoAEO2RoudxXWUz"><b>online</b></a> <a target="_blank" href="https://wandbox.org/permlink/hxcSxCPPLHpZMxjS"><b>online</b></a>

View File

@ -1 +1 @@
<a target="_blank" href="https://wandbox.org/permlink/KtW1m39B30RYkl5h"><b>online</b></a> <a target="_blank" href="https://wandbox.org/permlink/xbnldrrN05tKIOEv"><b>online</b></a>

View File

@ -1 +1 @@
<a target="_blank" href="https://wandbox.org/permlink/0W6xYpQWS5Kd64CF"><b>online</b></a> <a target="_blank" href="https://wandbox.org/permlink/gDQPYFxMrvD7RK4z"><b>online</b></a>

View File

@ -1 +1 @@
<a target="_blank" href="https://wandbox.org/permlink/iHSlXjtjhgO9Q1Tw"><b>online</b></a> <a target="_blank" href="https://wandbox.org/permlink/vVY4F4xKC3v6pG6F"><b>online</b></a>

View File

@ -1 +1 @@
<a target="_blank" href="https://wandbox.org/permlink/aIuHXNvIdSGowMgG"><b>online</b></a> <a target="_blank" href="https://wandbox.org/permlink/Q2GTzxF8NA10kVvD"><b>online</b></a>

View File

@ -1 +1 @@
<a target="_blank" href="https://wandbox.org/permlink/k52yOvuKAXPQl1ou"><b>online</b></a> <a target="_blank" href="https://wandbox.org/permlink/6LRjg1bqwchPUoDx"><b>online</b></a>

View File

@ -1 +1 @@
<a target="_blank" href="https://wandbox.org/permlink/mcjh1kDXXkzq7TxM"><b>online</b></a> <a target="_blank" href="https://wandbox.org/permlink/JMDd9jiP0flRKJ6C"><b>online</b></a>

View File

@ -1 +1 @@
<a target="_blank" href="https://wandbox.org/permlink/6tH3hnp53iVzAQZQ"><b>online</b></a> <a target="_blank" href="https://wandbox.org/permlink/HdlqwPk8bDfrZ4AE"><b>online</b></a>

View File

@ -1 +1 @@
<a target="_blank" href="https://wandbox.org/permlink/3OPLSVPyweUyEHaX"><b>online</b></a> <a target="_blank" href="https://wandbox.org/permlink/GHVHgDpT5vx0KMPD"><b>online</b></a>

View File

@ -1 +1 @@
<a target="_blank" href="https://wandbox.org/permlink/KtH6hJIe10abhHMi"><b>online</b></a> <a target="_blank" href="https://wandbox.org/permlink/DyMiKrkKMwd3R7OU"><b>online</b></a>

View File

@ -1 +1 @@
<a target="_blank" href="https://wandbox.org/permlink/zIQBGY6fKqiMmbvb"><b>online</b></a> <a target="_blank" href="https://wandbox.org/permlink/p9P3Ph8mdxMON6SY"><b>online</b></a>

View File

@ -1 +1 @@
<a target="_blank" href="https://wandbox.org/permlink/QEbpCnjGIpFWmYbE"><b>online</b></a> <a target="_blank" href="https://wandbox.org/permlink/yMxKrJfRedlFygJD"><b>online</b></a>

View File

@ -1 +1 @@
<a target="_blank" href="https://wandbox.org/permlink/AcEmkGmmmz0dPdHW"><b>online</b></a> <a target="_blank" href="https://wandbox.org/permlink/zaexgkNdH3HYJm8D"><b>online</b></a>

View File

@ -1 +1 @@
<a target="_blank" href="https://wandbox.org/permlink/65ClUAO2rdvXIuKi"><b>online</b></a> <a target="_blank" href="https://wandbox.org/permlink/eQ0YI8wWcMIHtBCS"><b>online</b></a>

View File

@ -1 +1 @@
<a target="_blank" href="https://wandbox.org/permlink/x9qygfrgrfjgjNpC"><b>online</b></a> <a target="_blank" href="https://wandbox.org/permlink/SD62jUgeIuudweZu"><b>online</b></a>

View File

@ -1 +1 @@
<a target="_blank" href="https://wandbox.org/permlink/G48ghomtqfwbG4OB"><b>online</b></a> <a target="_blank" href="https://wandbox.org/permlink/gG3bN97HOF04Xw6S"><b>online</b></a>

View File

@ -1 +1 @@
<a target="_blank" href="https://wandbox.org/permlink/8OiyguvJR3l15ail"><b>online</b></a> <a target="_blank" href="https://wandbox.org/permlink/WSnobkZJZHUPUIRF"><b>online</b></a>

View File

@ -1 +1 @@
<a target="_blank" href="https://wandbox.org/permlink/099bRQB6gKnhVuVl"><b>online</b></a> <a target="_blank" href="https://wandbox.org/permlink/GGoqGtqEzxAsAKnI"><b>online</b></a>

View File

@ -1 +1 @@
<a target="_blank" href="https://wandbox.org/permlink/9ESgIBWRarZRJvCw"><b>online</b></a> <a target="_blank" href="https://wandbox.org/permlink/vky6QCTCqtUnNVlD"><b>online</b></a>

View File

@ -1 +1 @@
<a target="_blank" href="https://wandbox.org/permlink/AQubfCmv848Q66Zi"><b>online</b></a> <a target="_blank" href="https://wandbox.org/permlink/aQjZSjuuDUxXQCjJ"><b>online</b></a>

View File

@ -1 +1 @@
<a target="_blank" href="https://wandbox.org/permlink/4bn447WQbTERfBaL"><b>online</b></a> <a target="_blank" href="https://wandbox.org/permlink/moO4IdryeGS8QmKo"><b>online</b></a>

View File

@ -1 +1 @@
<a target="_blank" href="https://wandbox.org/permlink/qtfoxfHO7u4eKMcO"><b>online</b></a> <a target="_blank" href="https://wandbox.org/permlink/Q7O1liz5QrgQynqQ"><b>online</b></a>

View File

@ -1 +1 @@
<a target="_blank" href="https://wandbox.org/permlink/AHKW5EMQN4YQ68TY"><b>online</b></a> <a target="_blank" href="https://wandbox.org/permlink/AjdbchxfTsN9PHCL"><b>online</b></a>

View File

@ -1 +1 @@
<a target="_blank" href="https://wandbox.org/permlink/J0KoQF8sOpdMg4kN"><b>online</b></a> <a target="_blank" href="https://wandbox.org/permlink/TdJfkKx0RAH5NB62"><b>online</b></a>

View File

@ -1 +1 @@
<a target="_blank" href="https://wandbox.org/permlink/uuQK0DAjhbSd96K6"><b>online</b></a> <a target="_blank" href="https://wandbox.org/permlink/GG9VzOZh1MDeTSsK"><b>online</b></a>

View File

@ -1 +1 @@
<a target="_blank" href="https://wandbox.org/permlink/5NtCbAfPzCmmPd5S"><b>online</b></a> <a target="_blank" href="https://wandbox.org/permlink/LtqaiI6oRplSg0KI"><b>online</b></a>

View File

@ -1 +1 @@
<a target="_blank" href="https://wandbox.org/permlink/frQdC0nigwUVSZ21"><b>online</b></a> <a target="_blank" href="https://wandbox.org/permlink/ddVSXnbULrNrCbRs"><b>online</b></a>

View File

@ -1 +1 @@
<a target="_blank" href="https://wandbox.org/permlink/M4EHlf0MaujBQlub"><b>online</b></a> <a target="_blank" href="https://wandbox.org/permlink/QjVgxx0bwbKuE9HI"><b>online</b></a>

View File

@ -1 +1 @@
<a target="_blank" href="https://wandbox.org/permlink/G1pg9ZBD5n15TZli"><b>online</b></a> <a target="_blank" href="https://wandbox.org/permlink/eA1KrytMlQl1SURe"><b>online</b></a>

View File

@ -1 +1 @@
<a target="_blank" href="https://wandbox.org/permlink/eKlCbdm2UdqXs3hS"><b>online</b></a> <a target="_blank" href="https://wandbox.org/permlink/jVaWWe3kAjKKn99V"><b>online</b></a>

View File

@ -1 +1 @@
<a target="_blank" href="https://wandbox.org/permlink/QxtxaO6JZAMJPutC"><b>online</b></a> <a target="_blank" href="https://wandbox.org/permlink/UvdMlXdPnXFUq1lJ"><b>online</b></a>

View File

@ -1 +1 @@
<a target="_blank" href="https://wandbox.org/permlink/2rHTkWYA0OUwkKBQ"><b>online</b></a> <a target="_blank" href="https://wandbox.org/permlink/N1nlz2liDCmBn40h"><b>online</b></a>

View File

@ -1 +1 @@
<a target="_blank" href="https://wandbox.org/permlink/fYEXWvuxjViaPZFS"><b>online</b></a> <a target="_blank" href="https://wandbox.org/permlink/eoHfSYf04soRkOto"><b>online</b></a>

View File

@ -1 +1 @@
<a target="_blank" href="https://wandbox.org/permlink/Qr8iIvIRnudssTvd"><b>online</b></a> <a target="_blank" href="https://wandbox.org/permlink/oNhgDq5ejDl5RyqW"><b>online</b></a>

View File

@ -1 +1 @@
<a target="_blank" href="https://wandbox.org/permlink/ObU2cC9WrntLk8Zx"><b>online</b></a> <a target="_blank" href="https://wandbox.org/permlink/LdmbgtdndQw81wQU"><b>online</b></a>

View File

@ -1 +1 @@
<a target="_blank" href="https://wandbox.org/permlink/TlWdaDctHaHnyFBm"><b>online</b></a> <a target="_blank" href="https://wandbox.org/permlink/kp99ButEWpuNxPbq"><b>online</b></a>

View File

@ -1 +1 @@
<a target="_blank" href="https://wandbox.org/permlink/PF6TEhsiazggimil"><b>online</b></a> <a target="_blank" href="https://wandbox.org/permlink/oUdIj3ZSbg7UCIuz"><b>online</b></a>

View File

@ -14,7 +14,7 @@ int main()
json j_object = {{"one", 1}, {"two", 2}}; json j_object = {{"one", 1}, {"two", 2}};
json j_array = {1, 2, 4, 8, 16}; json j_array = {1, 2, 4, 8, 16};
json j_string = "Hello, world"; json j_string = "Hello, world";
json j_binary = json::binary_array({1, 2, 3}); json j_binary = json::binary({1, 2, 3});
// call is_array() // call is_array()
std::cout << std::boolalpha; std::cout << std::boolalpha;

View File

@ -1 +1 @@
<a target="_blank" href="https://wandbox.org/permlink/qO60NqUznleA1S7v"><b>online</b></a> <a target="_blank" href="https://wandbox.org/permlink/2ZgSEJ7UBJ9d4H6b"><b>online</b></a>

View File

@ -14,7 +14,7 @@ int main()
json j_object = {{"one", 1}, {"two", 2}}; json j_object = {{"one", 1}, {"two", 2}};
json j_array = {1, 2, 4, 8, 16}; json j_array = {1, 2, 4, 8, 16};
json j_string = "Hello, world"; json j_string = "Hello, world";
json j_binary = json::binary_array({1, 2, 3}); json j_binary = json::binary({1, 2, 3});
// call is_binary() // call is_binary()
std::cout << std::boolalpha; std::cout << std::boolalpha;

View File

@ -1 +1 @@
<a target="_blank" href="https://wandbox.org/permlink/xR6eTQqSySLjtpn6"><b>online</b></a> <a target="_blank" href="https://wandbox.org/permlink/to5RDM1vhrDMUfVv"><b>online</b></a>

View File

@ -14,7 +14,7 @@ int main()
json j_object = {{"one", 1}, {"two", 2}}; json j_object = {{"one", 1}, {"two", 2}};
json j_array = {1, 2, 4, 8, 16}; json j_array = {1, 2, 4, 8, 16};
json j_string = "Hello, world"; json j_string = "Hello, world";
json j_binary = json::binary_array({1, 2, 3}); json j_binary = json::binary({1, 2, 3});
// call is_boolean() // call is_boolean()
std::cout << std::boolalpha; std::cout << std::boolalpha;

View File

@ -1 +1 @@
<a target="_blank" href="https://wandbox.org/permlink/QVbXnPfNZdvuDHwy"><b>online</b></a> <a target="_blank" href="https://wandbox.org/permlink/20OXaCBWTM1dhFmv"><b>online</b></a>

View File

@ -14,7 +14,7 @@ int main()
json j_object = {{"one", 1}, {"two", 2}}; json j_object = {{"one", 1}, {"two", 2}};
json j_array = {1, 2, 4, 8, 16}; json j_array = {1, 2, 4, 8, 16};
json j_string = "Hello, world"; json j_string = "Hello, world";
json j_binary = json::binary_array({1, 2, 3}); json j_binary = json::binary({1, 2, 3});
// call is_discarded() // call is_discarded()
std::cout << std::boolalpha; std::cout << std::boolalpha;

View File

@ -1 +1 @@
<a target="_blank" href="https://wandbox.org/permlink/jg033y5pdOFOst14"><b>online</b></a> <a target="_blank" href="https://wandbox.org/permlink/rTNvfIpTXdFXIe20"><b>online</b></a>

View File

@ -14,7 +14,7 @@ int main()
json j_object = {{"one", 1}, {"two", 2}}; json j_object = {{"one", 1}, {"two", 2}};
json j_array = {1, 2, 4, 8, 16}; json j_array = {1, 2, 4, 8, 16};
json j_string = "Hello, world"; json j_string = "Hello, world";
json j_binary = json::binary_array({1, 2, 3}); json j_binary = json::binary({1, 2, 3});
// call is_null() // call is_null()
std::cout << std::boolalpha; std::cout << std::boolalpha;

View File

@ -1 +1 @@
<a target="_blank" href="https://wandbox.org/permlink/uDLxYO1TseoNS5Iu"><b>online</b></a> <a target="_blank" href="https://wandbox.org/permlink/GCQOJn7fTbm6kPBo"><b>online</b></a>

View File

@ -14,7 +14,7 @@ int main()
json j_object = {{"one", 1}, {"two", 2}}; json j_object = {{"one", 1}, {"two", 2}};
json j_array = {1, 2, 4, 8, 16}; json j_array = {1, 2, 4, 8, 16};
json j_string = "Hello, world"; json j_string = "Hello, world";
json j_binary = json::binary_array({1, 2, 3}); json j_binary = json::binary({1, 2, 3});
// call is_number() // call is_number()
std::cout << std::boolalpha; std::cout << std::boolalpha;

View File

@ -1 +1 @@
<a target="_blank" href="https://wandbox.org/permlink/a7j4EG9Hvjbby3x0"><b>online</b></a> <a target="_blank" href="https://wandbox.org/permlink/guySOWaTCKiXcueC"><b>online</b></a>

View File

@ -14,7 +14,7 @@ int main()
json j_object = {{"one", 1}, {"two", 2}}; json j_object = {{"one", 1}, {"two", 2}};
json j_array = {1, 2, 4, 8, 16}; json j_array = {1, 2, 4, 8, 16};
json j_string = "Hello, world"; json j_string = "Hello, world";
json j_binary = json::binary_array({1, 2, 3}); json j_binary = json::binary({1, 2, 3});
// call is_number_float() // call is_number_float()
std::cout << std::boolalpha; std::cout << std::boolalpha;

View File

@ -1 +1 @@
<a target="_blank" href="https://wandbox.org/permlink/cT9J60hwwflg88M9"><b>online</b></a> <a target="_blank" href="https://wandbox.org/permlink/371XB9Jo3cwHDIBc"><b>online</b></a>

Some files were not shown because too many files have changed in this diff Show More