Unverified Commit 36e5ecf6 authored by Niels Lohmann's avatar Niels Lohmann

Merge branch 'release/3.9.0'

parents fbec662a e110667d
#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
Checks: '-*,
bugprone-*,
cert-*,
clang-analyzer-*,
google-*,
-google-runtime-references,
Checks: '*,
-cppcoreguidelines-avoid-goto,
-cppcoreguidelines-avoid-magic-numbers,
-cppcoreguidelines-macro-usage,
-fuchsia-default-arguments-calls,
-fuchsia-default-arguments-declarations,
-fuchsia-overloaded-operator,
-google-explicit-constructor,
hicpp-*,
-google-runtime-references,
-hicpp-avoid-goto,
-hicpp-explicit-conversions,
-hicpp-no-array-decay,
-hicpp-uppercase-literal-suffix,
-hicpp-explicit-conversions,
misc-*,
-misc-non-private-member-variables-in-classes,
llvm-*,
-llvm-header-guard,
modernize-*,
-llvm-include-order,
-misc-non-private-member-variables-in-classes,
-modernize-use-trailing-return-type,
performance-*,
portability-*,
readability-*,
-readability-magic-numbers,
-readability-uppercase-literal-suffix'
......
......@@ -47,7 +47,7 @@ assignees: ''
<!-- Please add an `x` to the respective line. -->
- [ ] latest release version 3.7.3
- [ ] latest release version 3.9.0
- [ ] other release - please state the version: ___
- [ ] the `develop` branch
......
---
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. -->
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
---
name: Question
about: Ask a question regarding the library.
title: ''
labels: 'kind: question'
assignees: ''
---
<!-- Provide a concise summary of the issue in the title above. -->
#### 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 -->
#### Can you provide a small code example?
<!-- Please understand that we cannot analyze and debug large code bases. -->
#### 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
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
......@@ -3,8 +3,7 @@ name: Windows
on: [push, pull_request]
jobs:
build:
msvc2019:
runs-on: windows-latest
steps:
......@@ -15,3 +14,55 @@ jobs:
run: cmake --build build --parallel 10
- name: test
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
......@@ -22,7 +22,7 @@ benchmarks/files/numbers/*.json
.wsjcpp/*
.idea
cmake-build-debug
/cmake-build-*
test/test-*
/.vs
......@@ -32,3 +32,4 @@ doc/mkdocs/docs/images
doc/mkdocs/docs/examples
doc/mkdocs/site
doc/mkdocs/docs/__pycache__/
doc/xml
......@@ -10,17 +10,6 @@ sudo: required
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 #
################
......@@ -129,6 +118,9 @@ matrix:
env:
- SPECIAL=coverity
- 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
......@@ -150,6 +142,14 @@ matrix:
- os: osx
osx_image: xcode11.2
- os: osx
osx_image: xcode12
- os: osx
osx_image: xcode12
env:
- IMPLICIT_CONVERSIONS=OFF
# Linux / GCC
- os: linux
......@@ -208,6 +208,16 @@ matrix:
sources: ['ubuntu-toolchain-r-test']
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
compiler: gcc
env:
......@@ -320,10 +330,12 @@ script:
- if [[ "${COMPILER}" != "" ]]; then export CXX=${COMPILER}; fi
# by default, use the single-header version
- if [[ "${MULTIPLE_HEADERS}" == "" ]]; then export MULTIPLE_HEADERS=OFF; fi
# by default, use implicit conversions
- if [[ "${IMPLICIT_CONVERSIONS}" == "" ]]; then export IMPLICIT_CONVERSIONS=ON; fi
# compile and execute unit tests
- mkdir -p build && cd build
- cmake .. ${CMAKE_OPTIONS} -DJSON_MultipleHeaders=${MULTIPLE_HEADERS} -DJSON_BuildTests=On -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
- cd ..
......
......@@ -4,7 +4,7 @@ cmake_minimum_required(VERSION 3.1)
## PROJECT
## name and version
##
project(nlohmann_json VERSION 3.8.0 LANGUAGES CXX)
project(nlohmann_json VERSION 3.9.0 LANGUAGES CXX)
##
## INCLUDE
......@@ -15,9 +15,16 @@ include(ExternalProject)
##
## 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_Install "Install CMake targets during install step." ON)
option(JSON_MultipleHeaders "Use non-amalgamated version of the library." OFF)
option(JSON_ImplicitConversions "Enable implicit conversions." ON)
##
## CONFIGURATION
......@@ -42,6 +49,10 @@ else()
message(STATUS "Using the single-header code from ${NLOHMANN_JSON_INCLUDE_BUILD_DIR}")
endif()
if (NOT JSON_ImplicitConversions)
message(STATUS "Implicit conversions are disabled")
endif()
##
## TARGET
## create target and add include path
......@@ -54,6 +65,12 @@ else()
target_compile_features(${NLOHMANN_JSON_TARGET_NAME} INTERFACE cxx_std_11)
endif()
target_compile_definitions(
${NLOHMANN_JSON_TARGET_NAME}
INTERFACE
JSON_USE_IMPLICIT_CONVERSIONS=$<BOOL:${JSON_ImplicitConversions}>
)
target_include_directories(
${NLOHMANN_JSON_TARGET_NAME}
INTERFACE
......@@ -73,6 +90,12 @@ if (MSVC)
)
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
## create and configure the unit test target
......@@ -133,4 +156,8 @@ endif()
NAMESPACE ${PROJECT_NAME}::
DESTINATION ${NLOHMANN_JSON_CONFIG_INSTALL_DIR}
)
install(
FILES "${CMAKE_BINARY_DIR}/${PROJECT_NAME}.pc"
DESTINATION lib/pkgconfig
)
endif()
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
......@@ -7,6 +7,7 @@ environment:
platform: x86
CXX_FLAGS: ""
LINKER_FLAGS: ""
CMAKE_OPTIONS: ""
GENERATOR: Visual Studio 14 2015
- APPVEYOR_BUILD_WORKER_IMAGE: Visual Studio 2017
......@@ -14,6 +15,7 @@ environment:
platform: x86
CXX_FLAGS: ""
LINKER_FLAGS: ""
CMAKE_OPTIONS: ""
GENERATOR: Visual Studio 15 2017
- APPVEYOR_BUILD_WORKER_IMAGE: Visual Studio 2019
......@@ -21,6 +23,7 @@ environment:
platform: x86
CXX_FLAGS: ""
LINKER_FLAGS: ""
CMAKE_OPTIONS: ""
GENERATOR: Visual Studio 16 2019
- APPVEYOR_BUILD_WORKER_IMAGE: Visual Studio 2019
......@@ -28,6 +31,7 @@ environment:
platform: x64
CXX_FLAGS: ""
LINKER_FLAGS: ""
CMAKE_OPTIONS: ""
GENERATOR: Visual Studio 16 2019
- APPVEYOR_BUILD_WORKER_IMAGE: Visual Studio 2015
......@@ -36,6 +40,7 @@ environment:
platform: x86
CXX_FLAGS: ""
LINKER_FLAGS: ""
CMAKE_OPTIONS: ""
GENERATOR: Ninja
- APPVEYOR_BUILD_WORKER_IMAGE: Visual Studio 2015
......@@ -44,6 +49,7 @@ environment:
platform: x86
CXX_FLAGS: ""
LINKER_FLAGS: ""
CMAKE_OPTIONS: ""
GENERATOR: Ninja
- APPVEYOR_BUILD_WORKER_IMAGE: Visual Studio 2015
......@@ -51,6 +57,7 @@ environment:
platform: x86
CXX_FLAGS: ""
LINKER_FLAGS: ""
CMAKE_OPTIONS: ""
GENERATOR: Visual Studio 14 2015
- APPVEYOR_BUILD_WORKER_IMAGE: Visual Studio 2015
......@@ -59,6 +66,7 @@ environment:
name: with_win_header
CXX_FLAGS: ""
LINKER_FLAGS: ""
CMAKE_OPTIONS: ""
GENERATOR: Visual Studio 14 2015
- APPVEYOR_BUILD_WORKER_IMAGE: Visual Studio 2017
......@@ -66,6 +74,7 @@ environment:
platform: x86
CXX_FLAGS: "/permissive- /std:c++latest /utf-8"
LINKER_FLAGS: ""
CMAKE_OPTIONS: ""
GENERATOR: Visual Studio 15 2017
- APPVEYOR_BUILD_WORKER_IMAGE: Visual Studio 2019
......@@ -73,6 +82,15 @@ environment:
platform: x86
CXX_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
- APPVEYOR_BUILD_WORKER_IMAGE: Visual Studio 2015
......@@ -80,6 +98,7 @@ environment:
platform: x64
CXX_FLAGS: ""
LINKER_FLAGS: ""
CMAKE_OPTIONS: ""
GENERATOR: Visual Studio 14 2015
- APPVEYOR_BUILD_WORKER_IMAGE: Visual Studio 2017
......@@ -87,6 +106,7 @@ environment:
platform: x64
CXX_FLAGS: "/permissive- /std:c++latest /Zc:__cplusplus /utf-8 /F4000000"
LINKER_FLAGS: "/STACK:4000000"
CMAKE_OPTIONS: ""
GENERATOR: Visual Studio 15 2017
- APPVEYOR_BUILD_WORKER_IMAGE: Visual Studio 2019
......@@ -94,6 +114,7 @@ environment:
platform: x64
CXX_FLAGS: ""
LINKER_FLAGS: ""
CMAKE_OPTIONS: ""
GENERATOR: Visual Studio 16 2019
init:
......@@ -112,7 +133,7 @@ before_build:
# 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") { "#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" -DJSON_BuildTests=On) 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)
- 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:
- cmake --build . --config "%configuration%"
......
find_package(Git)
set(JSON_TEST_DATA_URL https://github.com/nlohmann/json_test_data)
set(JSON_TEST_DATA_VERSION 2.0.0)
# 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
COMMENT "Downloading test data from ${JSON_TEST_DATA_URL} (v${JSON_TEST_DATA_VERSION})"
WORKING_DIRECTORY ${CMAKE_BINARY_DIR}
)
set(JSON_TEST_DATA_VERSION 3.0.0)
# 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")
# if variable is set, use test data from given directory rather than downloading them
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
COMMENT "Downloading test data from ${JSON_TEST_DATA_URL} (v${JSON_TEST_DATA_VERSION})"
WORKING_DIRECTORY ${CMAKE_BINARY_DIR}
)
# 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")
endif()
# determine the operating system (for debug and support purposes)
find_program(UNAME_COMMAND uname)
......
Name: ${PROJECT_NAME}
Description: JSON for Modern C++
Version: ${PROJECT_VERSION}
Cflags: -I${CMAKE_INSTALL_PREFIX}/${CMAKE_INSTALL_INCLUDEDIR}
......@@ -5,7 +5,7 @@
#---------------------------------------------------------------------------
DOXYFILE_ENCODING = UTF-8
PROJECT_NAME = "JSON for Modern C++"
PROJECT_NUMBER = 3.8.0
PROJECT_NUMBER = 3.9.0
PROJECT_BRIEF =
PROJECT_LOGO =
OUTPUT_DIRECTORY = .
......
......@@ -43,7 +43,7 @@ check_output: $(EXAMPLES:.cpp=.test)
clean:
rm -fr me.nlohmann.json.docset html $(EXAMPLES:.cpp=)
rm -fr me.nlohmann.json.docset html xml $(EXAMPLES:.cpp=)
##########################################################################
......
doc/avatars.png

1.1 MB | W: | H:

doc/avatars.png

1.12 MB | W: | H:

doc/avatars.png
doc/avatars.png
doc/avatars.png
doc/avatars.png
  • 2-up
  • Swipe
  • Onion skin
<a target="_blank" href="https://wandbox.org/permlink/EezQxM0Nzi8tTUEe"><b>online</b></a>
\ No newline at end of file
<a target="_blank" href="https://wandbox.org/permlink/shE8T6phAQiEzAad"><b>online</b></a>
\ No newline at end of file
......@@ -2,16 +2,16 @@
"compiler": {
"c++": "201103",
"family": "clang",
"version": "11.0.3 (clang-1103.0.32.62)"
"version": "12.0.0 (clang-1200.0.22.19)"
},
"copyright": "(C) 2013-2017 Niels Lohmann",
"copyright": "(C) 2013-2020 Niels Lohmann",
"name": "JSON for Modern C++",
"platform": "apple",
"url": "https://github.com/nlohmann/json",
"version": {
"major": 3,
"minor": 8,
"minor": 9,
"patch": 0,
"string": "3.8.0"
"string": "3.9.0"
}
}
......@@ -332,4 +332,4 @@ Note that this table only lists those exceptions thrown due to the type. For ins
@author [Niels Lohmann](http://nlohmann.me)
@see https://github.com/nlohmann/json to download the source code
@version 3.8.0
@version 3.9.0
doc/json.gif

1.62 MB | W: | H:

doc/json.gif

1.63 MB | W: | H:

doc/json.gif
doc/json.gif
doc/json.gif
doc/json.gif
  • 2-up
  • Swipe
  • Onion skin
# basic_json::dump
```cpp
string_t dump(const int indent = -1,
const char indent_char = ' ',
const bool ensure_ascii = false,
const error_handler_t error_handler = error_handler_t::strict) const
```
Serialization function for JSON values. The function tries to mimic
Python's `json.dumps()` function, and currently supports its `indent`
and `ensure_ascii` parameters.
## Parameters
`indent` (in)
: If `indent` is nonnegative, then array elements and object
members will be pretty-printed with that indent level. An indent level of
`0` will only insert newlines. `-1` (the default) selects the most compact
representation.
`indent_char` (in)
: The character to use for indentation if `indent` is
greater than `0`. The default is ` ` (space).
`ensure_ascii` (in)
: If `ensure_ascii` is true, all non-ASCII characters
in the output are escaped with `\uXXXX` sequences, and the result consists
of ASCII characters only.
`error_handler` (in)
: how to react on decoding errors; there are three
possible values: `strict` (throws and exception in case a decoding error
occurs; default), `replace` (replace invalid UTF-8 sequences with U+FFFD),
and `ignore` (ignore invalid UTF-8 sequences during serialization; all
bytes are copied to the output unchanged).
## Return value
string containing the serialization of the JSON value
## Exception safety
Strong guarantee: if an exception is thrown, there are no
changes to any JSON value.
## Complexity
Linear.
## Notes
Binary values are serialized as object containing two keys:
- "bytes": an array of bytes as integers
- "subtype": the subtype as integer or `#!json null` if the binary has no subtype
## Example
??? example
The following example shows the effect of different `indent`,
`indent_char`, and `ensure_ascii` parameters to the result of the
serialization.
```cpp
--8<-- "examples/dump.cpp"
```
Output:
```json
--8<-- "examples/dump.output"
```
# basic_json
!!! note
This page is under construction.
Defined in header `<json.hpp>`
```cpp
template<template<typename, typename, typename...> class ObjectType,
template<typename, typename...> class ArrayType,
class StringType, class BooleanType, class NumberIntegerType,
class NumberUnsignedType, class NumberFloatType,
template<typename> class AllocatorType,
template<typename, typename = void> class JSONSerializer,
class BinaryType>
class basic_json
```
## Specializations
- json
- ordered_json
## Template parameters
- ObjectType
- ArrayType
- StringType
- BooleanType
- NumberIntegerType
- NumberUnsignedType
- NumberFloatType
- AllocatorType
- JSONSerializer
- BinaryType
## Iterator invalidation
## Member types
- value_t
- json_pointer
- json_serializer
- error_handler_t
- cbor_tag_handler_t
- initializer_list_t
- input_format_t
- json_sax_t
### Exceptions
- exception
- parse_error
- invalid_iterator
- type_error
- out_of_range
- other_error
### Container types
- value_type
- reference
- const_reference
- difference_type
- size_type
- allocator_type
- pointer
- const_pointer
- iterator
- const_iterator
- reverse_iterator
- const_reverse_iterator
### JSON value data types
- object_comparator_t
- object_t
- array_t
- string_t
- boolean_t
- number_integer_t
- number_unsigned_t
- number_float_t
- binary_t
### Parser callback
- parse_event_t
- parser_callback_t
## Member functions
- (constructor)
- (destructor)
- binary (static) - explicitly create a binary array
- array (static) - explicitly create an array
- object (static) - explicitly create an object
- operator= - copy assignment
### Object inspection
Functions to inspect the type of a JSON value.
- type - return the type of the JSON value
- is_primitive - return whether type is primitive
- is_structured - return whether type is structured
- is_null - return whether value is null
- is_boolean - return whether value is a boolean
- is_number - return whether value is a number
- is_number_integer - return whether value is an integer number
- is_number_unsigned - return whether value is an unsigned integer number
- is_number_float - return whether value is a floating-point number
- is_object - return whether value is an object
- is_array - return whether value is an array
- is_string - return whether value is a string
- is_binary - return whether value is a binary array
- is_discarded - return whether value is discarded
- operator value_t - return the type of the JSON value
### Value access
Direct access to the stored value of a JSON value.
- get - get a value
- get_to - get a value
- get_ptr - get a pointer value
- get_ref - get a reference value
- operator ValueType - get a value
- get_binary - get a binary value
### Element access
Access to the JSON value
- at - access specified array element with bounds checking
- at - access specified object element with bounds checking
- operator[] - access specified array element
- operator[] - access specified object element
- value - access specified object element with default value
- front - access the first element
- back - access the last element
- erase - remove elements
### Lookup
- find - find an element in a JSON object
- count - returns the number of occurrences of a key in a JSON object
- contains - check the existence of an element in a JSON object
### Iterators
- begin - returns an iterator to the first element
- cbegin - returns a const iterator to the first element
- end - returns an iterator to one past the last element
- cend - returns a const iterator to one past the last element
- rbegin - returns an iterator to the reverse-beginning
- rend - returns an iterator to the reverse-end
- crbegin - returns a const iterator to the reverse-beginning
- crend - returns a const iterator to the reverse-end
- items - wrapper to access iterator member functions in range-based for
### Capacity
- empty - checks whether the container is empty
- size - returns the number of elements
- max_size - returns the maximum possible number of elements
### Modifiers
- clear - clears the contents
- push_back - add an object to an array
- operator+= - add an object to an array
- push_back - add an object to an object
- operator+= - add an object to an object
- emplace_back - add an object to an array
- emplace - add an object to an object if key does not exist
- insert - inserts element
- update - updates a JSON object from another object, overwriting existing keys
- swap - exchanges the values
### Lexicographical comparison operators
- operator== - comparison: equal
- operator!= - comparison: not equal
- operator< - comparison: less than
- operator<= - comparison: less than or equal
- operator> - comparison: greater than
- operator>= - comparison: greater than or equal
### Serialization
- [**dump**](dump.md) - serialization
- to_string - user-defined to_string function for JSON values
### Deserialization
- [**parse**](parse.md) - deserialize from a compatible input
- accept - check if the input is valid JSON
- sax_parse - generate SAX events
### Convenience functions
- type_name - return the type as string
### JSON Pointer functions
- at - access specified object element with bounds checking via JSON Pointer
- operator[] - access specified element via JSON Pointer
- value - access specified object element with default value via JSON Pointer
- flatten - return flattened JSON value
- unflatten - unflatten a previously flattened JSON value
### JSON Patch functions
- patch - applies a JSON patch
- diff (static) - creates a diff as a JSON patch
### JSON Merge Patch functions
- merge_patch - applies a JSON Merge Patch
## Static functions
- [**meta**](meta.md) - returns version information on the library
- get_allocator - returns the allocator associated with the container
### Binary formats
- to_cbor - create a CBOR serialization of a given JSON value
- to_msgpack - create a MessagePack serialization of a given JSON value
- to_ubjson - create a UBJSON serialization of a given JSON value
- to_bson - create a BSON serialization of a given JSON value
- from_cbor - create a JSON value from an input in CBOR format
- from_msgpack - create a JSON value from an input in MessagePack format
- from_ubjson - create a JSON value from an input in UBJSON format
- from_bson - create a JSON value from an input in BSON format
## Non-member functions
- operator<<(std::ostream&) - serialize to stream
- operator>>(std::istream&) - deserialize from stream
## Literals
- operator""_json
- operator""_json_pointer
## Helper classes
- std::hash<nlohmann::json\>
- std::less<nlohmann::value_t\>
- std::swap<nlohmann::json\>
# basic_json::meta
```cpp
static basic_json meta();
```
This function returns a JSON object with information about the library,
including the version number and information on the platform and compiler.
## Return value
JSON object holding version information
key | description
----------- | ---------------
`compiler` | Information on the used compiler. It is an object with the following keys: `c++` (the used C++ standard), `family` (the compiler family; possible values are `clang`, `icc`, `gcc`, `ilecpp`, `msvc`, `pgcpp`, `sunpro`, and `unknown`), and `version` (the compiler version).
`copyright` | The copyright line for the library as string.
`name` | The name of the library as string.
`platform` | The used platform as string. Possible values are `win32`, `linux`, `apple`, `unix`, and `unknown`.
`url` | The URL of the project as string.
`version` | The version of the library. It is an object with the following keys: `major`, `minor`, and `patch` as defined by [Semantic Versioning](http://semver.org), and `string` (the version string).
## Exception safety
Strong guarantee: if an exception is thrown, there are no
changes to any JSON value.
## Complexity
Constant.
## Example
The following code shows an example output of the `meta()`
function.
```cpp
--8<-- "examples/meta.cpp"
```
Output:
```json
--8<-- "examples/meta.output"
```
# basic_json::parse
```cpp
// (1)
template<typename InputType>
static basic_json parse(InputType&& i,
const parser_callback_t cb = nullptr,
const bool allow_exceptions = true,
const bool ignore_comments = false)
// (2)
template<typename IteratorType>
static basic_json parse(IteratorType first,
IteratorType last,
const parser_callback_t cb = nullptr,
const bool allow_exceptions = true,
const bool ignore_comments = false)
```
1. Deserialize from a compatible input.
2. Deserialize from a pair of character iterators
The value_type of the iterator must be a integral type with size of 1, 2 or
4 bytes, which will be interpreted respectively as UTF-8, UTF-16 and UTF-32.
## Template parameters
`InputType`
: A compatible input, for instance:
- an `std::istream` object
- a `FILE` pointer
- a C-style array of characters
- a pointer to a null-terminated string of single byte characters
- an object `obj` for which `begin(obj)` and `end(obj)` produces a valid pair of
iterators.
`IteratorType`
: Description
## Parameters
`i` (in)
: Input to parse from.
`cb` (in)
: a parser callback function of type `parser_callback_t`
which is used to control the deserialization by filtering unwanted values
(optional)
`allow_exceptions` (in)
: whether to throw exceptions in case of a parse error (optional, `#!cpp true` by default)
`ignore_comments` (in)
: whether comments should be ignored and treated
like whitespace (`#!cpp true`) or yield a parse error (`#!cpp false`); (optional, `#!cpp false` by
default)
`first` (in)
: iterator to start of character range
`last` (in)
: iterator to end of character range
## Return value
Deserialized JSON value; in case of a parse error and `allow_exceptions`
set to `#!cpp false`, the return value will be `value_t::discarded`.
## Exception safety
## Complexity
Linear in the length of the input. The parser is a predictive
LL(1) parser. The complexity can be higher if the parser callback function
`cb` or reading from (1) the input `i` or (2) the iterator range [`first`, `last`] has a super-linear complexity.
## Notes
(1) A UTF-8 byte order mark is silently ignored.
## Examples
??? example
The example below demonstrates the `parse()` function reading
from an array.
```cpp
--8<-- "examples/parse__array__parser_callback_t.cpp"
```
Output:
```json
--8<-- "examples/parse__array__parser_callback_t.output"
```
??? example
The example below demonstrates the `parse()` function with
and without callback function.
```cpp
--8<-- "examples/parse__string__parser_callback_t.cpp"
```
Output:
```json
--8<-- "examples/parse__string__parser_callback_t.output"
```
??? example
The example below demonstrates the `parse()` function with
and without callback function.
```cpp
--8<-- "examples/parse__istream__parser_callback_t.cpp"
```
Output:
```json
--8<-- "examples/parse__istream__parser_callback_t.output"
```
??? example
The example below demonstrates the `parse()` function reading
from a contiguous container.
```cpp
--8<-- "examples/parse__contiguouscontainer__parser_callback_t.cpp"
```
Output:
```json
--8<-- "examples/parse__contiguouscontainer__parser_callback_t.output"
```
## History
(1) version 2.0.3 (contiguous containers); version 3.9.0 allowed to ignore comments.
......@@ -81,6 +81,47 @@ Some important things:
* 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.
!!! note
At most 64 member variables can be passed to `NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE` or `NLOHMANN_DEFINE_TYPE_INTRUSIVE`.
??? example
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?
This requires a bit more advanced technique. But first, let's see how this conversion mechanism works:
......
......@@ -64,7 +64,6 @@ binary | *size*: 4294967296..18446744073709551615 | byte string (8 by
If NaN or Infinity are stored inside a JSON number, they are serialized properly. This behavior differs from the normal JSON serialization which serializes NaN or Infinity to `null`.
!!! info "Unused CBOR types"
The following CBOR types are not used in the conversion:
......@@ -77,13 +76,16 @@ binary | *size*: 4294967296..18446744073709551615 | byte string (8 by
- 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-precision floats (0xF9)
- break (0xFF)
!!! info "Tagged items"
Binary subtypes will be serialized as tagged items. See [binary values](../binary_values.md#cbor) for an example.
??? example
```cpp
......@@ -150,7 +152,6 @@ Double-Precision Float | number_float | 0xFB
- 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)
......@@ -159,6 +160,10 @@ Double-Precision Float | number_float | 0xFB
CBOR 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.
!!! warning "Tagged items"
Tagged items will throw a parse error by default. However, they can be ignored by passing `cbor_tag_handler_t::ignore` to function `from_cbor`.
??? example
```cpp
......
......@@ -31,7 +31,8 @@ number_unsigned | 128..255 | uint 8 | 0xCC
number_unsigned | 256..65535 | uint 16 | 0xCD
number_unsigned | 65536..4294967295 | uint 32 | 0xCE
number_unsigned | 4294967296..18446744073709551615 | uint 64 | 0xCF
number_float | *any value* | float 64 | 0xCB
number_float | *any value representable by a float* | float 32 | 0xCA
number_float | *any value NOT representable by a float* | float 64 | 0xCB
string | *length*: 0..31 | fixstr | 0xA0..0xBF
string | *length*: 32..255 | str 8 | 0xD9
string | *length*: 256..65535 | str 16 | 0xDA
......@@ -61,10 +62,6 @@ binary | *size*: 65536..4294967295 | bin 32 | 0xC6
- arrays with more than 4294967295 elements
- objects with more than 4294967295 elements
!!! info "Unused MessagePack types"
The following MessagePack types are not used in the conversion: float 32 (0xCA)
!!! info "NaN/infinity handling"
If NaN or Infinity are stored inside a JSON number, they are serialized properly. function which serializes NaN or Infinity to `null`.
......
......@@ -28,6 +28,7 @@ number_unsigned | 128..255 | uint8 | `U`
number_unsigned | 256..32767 | int16 | `I`
number_unsigned | 32768..2147483647 | int32 | `l`
number_unsigned | 2147483648..9223372036854775807 | int64 | `L`
number_unsigned | 2147483649..18446744073709551615 | high-precision | `H`
number_float | *any value* | float64 | `D`
string | *with shortest length indicator* | string | `S`
array | *see notes on optimized format* | array | `[`
......@@ -44,7 +45,6 @@ object | *see notes on optimized format* | map | `{`
The following values can **not** be converted to a UBJSON value:
- strings with more than 9223372036854775807 bytes (theoretical)
- unsigned integer numbers above 9223372036854775807
!!! info "Unused UBJSON markers"
......
......@@ -158,14 +158,14 @@ JSON does not have a binary type, and this library does not introduce a new type
### CBOR
[CBOR](binary_formats/cbor.md) supports binary values, but no subtypes. Any binary value will be serialized as byte strings. The library will choose the smallest representation using the length of the byte array.
[CBOR](binary_formats/cbor.md) supports binary values, but no subtypes. Subtypes will be serialized as tags. Any binary value will be serialized as byte strings. The library will choose the smallest representation using the length of the byte array.
??? example
Code:
```cpp
// create a binary value of subtype 42 (will be ignored by CBOR)
// create a binary value of subtype 42
json j;
j["binary"] = json::binary({0xCA, 0xFE, 0xBA, 0xBE}, 42);
......@@ -173,17 +173,18 @@ JSON does not have a binary type, and this library does not introduce a new type
auto v = json::to_cbor(j);
```
`v` is a `std::vector<std::uint8t>` with the following 13 elements:
`v` is a `std::vector<std::uint8t>` with the following 15 elements:
```c
0xA1 // map(1)
0x66 // text(6)
0x62 0x69 0x6E 0x61 0x72 0x79 // "binary"
0xD8 0x2A // tag(42)
0x44 // bytes(4)
0xCA 0xFE 0xBA 0xBE // content
```
Note the subtype (42) is **not** serialized, and deserializing `v` would yield the following value:
Note that the subtype is serialized as tag. However, parsing tagged values yield a parse error unless `json::cbor_tag_handler_t::ignore` is passed to `json::from_cbor`.
```json
{
......
# Comments
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.
2. This was not an oversight: Douglas Crockford [wrote on this](https://plus.google.com/118095276221607585885/posts/RK8qyGVaGSr) in May 2012:
> I removed comments from JSON because I saw people were using them to hold parsing directives, a practice which would have destroyed interoperability. I know that the lack of comments makes some people sad, but it shouldn't.
> Suppose you are using JSON to keep configuration files, which you would like to annotate. Go ahead and insert all the comments you like. Then pipe it through JSMin before handing it to your JSON parser.
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.
However, you can pass set parameter `ignore_comments` to `#!c true` in the parse function to ignore `//` or `/* */` comments. Comments will then be treated as whitespace.
!!! example
Consider the following JSON with comments.
```json
{
// update in 2006: removed Pluto
"planets": ["Mercury", "Venus", "Earth", "Mars",
"Jupiter", "Uranus", "Neptune" /*, "Pluto" */]
}
```
When calling `parse` without additional argument, a parse error exception is thrown. If `skip_comments` is set to `#! true`, the comments are skipped during parsing:
```cpp
#include <iostream>
#include "json.hpp"
using json = nlohmann::json;
int main()
{
std::string s = R"(
{
// update in 2006: removed Pluto
"planets": ["Mercury", "Venus", "Earth", "Mars",
"Jupiter", "Uranus", "Neptune" /*, "Pluto" */]
}
)";
try
{
json j = json::parse(s);
}
catch (json::exception &e)
{
std::cout << e.what() << std::endl;
}
json j = json::parse(s,
/* callback */ nullptr,
/* allow exceptions */ true,
/* skip_comments */ true);
std::cout << j.dump(2) << '\n';
}
```
Output:
```
[json.exception.parse_error.101] parse error at line 3, column 9:
syntax error while parsing object key - invalid literal;
last read: '<U+000A> {<U+000A> /'; expected string literal
```
```json
{
"planets": [
"Mercury",
"Venus",
"Earth",
"Mars",
"Jupiter",
"Uranus",
"Neptune"
]
}
```
\ No newline at end of file
# Checked access: at
## Overview
The `#!cpp at()` member function performs checked access; that is, it returns a reference to the desired value if it exists and throws a [`basic_json::out_of_range` exception](../../home/exceptions.md#out-of-range) otherwise.
??? example
Consider the following JSON value:
```json
{
"name": "Mary Smith",
"age": 42,
"hobbies": ["hiking", "reading"]
}
```
Assume the value is parsed to a `json` variable `j`.
| expression | value |
| ---------- | ----- |
| `#!cpp j` | `#!json {"name": "Mary Smith", "age": 42, "hobbies": ["hiking", "reading"]}` |
| `#!cpp j.at("name")` | `#!json "Mary Smith"` |
| `#!cpp j.at("age")` | `#!json 42` |
| `#!cpp j.at("hobbies")` | `#!json ["hiking", "reading"]` |
| `#!cpp j.at("hobbies").at(0)` | `#!json "hiking"` |
| `#!cpp j.at("hobbies").at(1)` | `#!json "reading"` |
The return value is a reference, so it can be modify the original value.
??? example
```cpp
j.at("name") = "John Smith";
```
This code produces the following JSON value:
```json
{
"name": "John Smith",
"age": 42,
"hobbies": ["hiking", "reading"]
}
```
When accessing an invalid index (i.e., and index greater than or equal to the array size) or the passed object key is non-existing, an exception is thrown.
??? example
```cpp
j.at("hobbies").at(3) = "cooking";
```
This code produces the following exception:
```
[json.exception.out_of_range.401] array index 3 is out of range
```
## Notes
!!! failure "Exceptions"
- `at` can only be used with objects (with a string argument) or with arrays (with a numeric argument). For other types, a [`basic_json::type_error`](../../home/exceptions.md#jsonexceptiontype_error304) is thrown.
- [`basic_json::out_of_range` exception](../../home/exceptions.md#out-of-range) exceptions are thrown if the provided key is not found in an object or the provided index is invalid.
## Summary
| scenario | non-const value | const value |
| -------- | ------------- | ----------- |
| access to existing object key | reference to existing value is returned | const reference to existing value is returned |
| access to valid array index | reference to existing value is returned | const reference to existing value is returned |
| access to non-existing object key | `basic_json::out_of_range` exception is thrown | `basic_json::out_of_range` exception is thrown |
| access to invalid array index | `basic_json::out_of_range` exception is thrown | `basic_json::out_of_range` exception is thrown |
# Access with default value: value
## Overview
In many situations such as configuration files, missing values are not exceptional, but may be treated as if a default value was present.
??? example
Consider the following JSON value:
```json
{
"logOutput": "result.log",
"append": true
}
```
Assume the value is parsed to a `json` variable `j`.
| expression | value |
| ---------- | ----- |
| `#!cpp j` | `#!json {"logOutput": "result.log", "append": true}` |
| `#!cpp j.value("logOutput", "logfile.log")` | `#!json "result.log"` |
| `#!cpp j.value("append", true)` | `#!json true` |
| `#!cpp j.value("append", false)` | `#!json true` |
| `#!cpp j.value("logLevel", "verbose")` | `#!json "verbose"` |
## Note
!!! failure "Exceptions"
- `value` can only be used with objects. For other types, a [`basic_json::type_error`](../../home/exceptions.md#jsonexceptiontype_error306) is thrown.
# Overview
There are many ways elements in a JSON value can be accessed:
- unchecked access via [`operator[]`](unchecked_access.md)
- checked access via [`at`](checked_access.md)
- access with default value via [`value`](default_value.md)
- iterators
- JSON pointers
# Unchecked access: operator[]
## Overview
Elements in a JSON object and a JSON array can be accessed via `#!cpp operator[]` similar to a `#!cpp std::map` and a `#!cpp std::vector`, respectively.
??? example
Consider the following JSON value:
```json
{
"name": "Mary Smith",
"age": 42,
"hobbies": ["hiking", "reading"]
}
```
Assume the value is parsed to a `json` variable `j`.
| expression | value |
| ---------- | ----- |
| `#!cpp j` | `#!json {"name": "Mary Smith", "age": 42, "hobbies": ["hiking", "reading"]}` |
| `#!cpp j["name"]` | `#!json "Mary Smith"` |
| `#!cpp j["age"]` | `#!json 42` |
| `#!cpp j["hobbies"]` | `#!json ["hiking", "reading"]` |
| `#!cpp j["hobbies"][0]` | `#!json "hiking"` |
| `#!cpp j["hobbies"][1]` | `#!json "reading"` |
The return value is a reference, so it can be modify the original value. In case the passed object key is non-existing, a `#!json null` value is inserted which can be immediately be overwritten.
??? example
```cpp
j["name"] = "John Smith";
j["maidenName"] = "Jones";
```
This code produces the following JSON value:
```json
{
"name": "John Smith",
"maidenName": "Jones",
"age": 42,
"hobbies": ["hiking", "reading"]
}
```
When accessing an invalid index (i.e., and index greater than or equal to the array size), the JSON array is resized such that the passed index is the new maximal index. Intermediate values are filled with `#!json null`.
??? example
```cpp
j["hobbies"][0] = "running";
j["hobbies"][3] = "cooking";
```
This code produces the following JSON value:
```json
{
"name": "John Smith",
"maidenName": "Jones",
"age": 42,
"hobbies": ["running", "reading", null, "cooking"]
}
```
## Notes
!!! info "Design rationale"
The library behaves differently to `#!cpp std::vector` and `#!cpp std::map`:
- `#!cpp std::vector::operator[]` never inserts a new element.
- `#!cpp std::map::operator[]` is not available for const values.
The type `#!cpp json` wraps all JSON value types. It would be impossible to remove `operator[]` for const objects. At the same time, inserting elements for non-const objects is really convenient as it avoids awkward `insert` calls. To this end, we decided to have an inserting non-const behavior for both arrays and objects.
!!! info
The access is unchecked. In case the passed object key does not exist or the passed array index is invalid, no exception is thrown.
!!! danger
- It is **undefined behavior** to access a const object with a non-existing key.
- It is **undefined behavior** to access a const array with an invalid index.
- In debug mode, an **assertion** will fire in both cases. You can disable assertions by defining the preprocessor symbol `#!cpp NDEBUG` or redefine the macro [`JSON_ASSERT(x)`](../macros.md#json_assertx).
!!! failure "Exceptions"
`operator[]` can only be used with objects (with a string argument) or with arrays (with a numeric argument). For other types, a [`basic_json::type_error`](../../home/exceptions.md#jsonexceptiontype_error305) is thrown.
## Summary
| scenario | non-const value | const value |
| -------- | ------------- | ----------- |
| access to existing object key | reference to existing value is returned | const reference to existing value is returned |
| access to valid array index | reference to existing value is returned | const reference to existing value is returned |
| access to non-existing object key | reference to newly inserted `#!json null` value is returned | **undefined behavior**; assertion in debug mode |
| access to invalid array index | reference to newly inserted `#!json null` value is returned; any index between previous maximal index and passed index are filled with `#!json null` | **undefined behavior**; assertion in debug mode |
# Supported Macros
Some aspects of the library can be configured by defining preprocessor macros before including the `json.hpp` header.
## `JSON_ASSERT(x)`
The default value is `#!cpp assert(x)`.
## `JSON_CATCH_USER(exception)`
This macro overrides `#!cpp catch` calls inside the library. The argument is the type of the exception to catch. As of version 3.8.0, the library only catches `std::out_of_range` exceptions internally to rethrow them as [`json::out_of_range`](../home/exceptions.md#out-of-range) exceptions. The macro is always followed by a scope.
See [Switch off exceptions](../home/exceptions.md#switch-off-exceptions) for an example.
## `JSON_NOEXCEPTION`
Exceptions can be switched off by defining the symbol `JSON_NOEXCEPTION`.
When defining `JSON_NOEXCEPTION`, `#!cpp try` is replaced by `#!cpp if (true)`,
`#!cpp catch` is replaced by `#!cpp if (false)`, and `#!cpp throw` is replaced by `#!cpp std::abort()`.
The same effect is achieved by setting the compiler flag `-fno-exceptions`.
## `JSON_SKIP_UNSUPPORTED_COMPILER_CHECK`
When defined, the library will not create a compile error when a known unsupported compiler is detected. This allows to use the library with compilers that do not fully support C++11 and may only work if unsupported features are not used.
## `JSON_THROW_USER(exception)`
This macro overrides `#!cpp throw` calls inside the library. The argument is the exception to be thrown. Note that `JSON_THROW_USER` should leave the current scope (e.g., by throwing or aborting), as continuing after it may yield undefined behavior.
See [Switch off exceptions](../home/exceptions.md#switch-off-exceptions) for an example.
## `JSON_TRY_USER`
This macro overrides `#!cpp try` calls inside the library. It has no arguments and is always followed by a scope.
See [Switch off exceptions](../home/exceptions.md#switch-off-exceptions) for an example.
## `JSON_USE_IMPLICIT_CONVERSIONS`
When defined to `0`, implicit conversions are switched off. By default, implicit conversions are switched on.
??? example
This is an example for an implicit conversion:
```cpp
json j = "Hello, world!";
std::string s = j;
```
When `JSON_USE_IMPLICIT_CONVERSIONS` is defined to `0`, the code above does no longer compile. Instead, it must be written like this:
```cpp
json j = "Hello, world!";
auto s = j.get<std::string>();
```
## `NLOHMANN_DEFINE_TYPE_INTRUSIVE(type, member...)`
This macro can be used to simplify the serialization/deserialization of types if (1) want to use a JSON object as serialization and (2) want to use the member variable names as object keys in that object.
The macro is to be defined inside of the class/struct to create code for. Unlike [`NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE`](#nlohmann_define_type_non_intrusivetype-member), it can access private members.
The first parameter is the name of the class/struct, and all remaining parameters name the members.
See [Simplify your life with macros](arbitrary_types.md#simplify-your-life-with-macros) for an example.
## `NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE(type, member...)`
This macro can be used to simplify the serialization/deserialization of types if (1) want to use a JSON object as serialization and (2) want to use the member variable names as object keys in that object.
The macro is to be defined inside of the namespace of the class/struct to create code for. Private members cannot be accessed. Use [`NLOHMANN_DEFINE_TYPE_INTRUSIVE`](#nlohmann_define_type_intrusivetype-member) in these scenarios.
The first parameter is the name of the class/struct, and all remaining parameters name the members.
See [Simplify your life with macros](arbitrary_types.md#simplify-your-life-with-macros) for an example.
## `NLOHMANN_JSON_SERIALIZE_ENUM(type, ...)`
This macro simplifies the serialization/deserialization of enum types. See [Specializing enum conversion](enum_conversion.md) for more information.
# Object Order
The [JSON standard](https://tools.ietf.org/html/rfc8259.html) defines objects as "an unordered collection of zero or more name/value pairs". As such, an implementation does not need to preserve any specific order of object keys.
The default type `nlohmann::json` uses a `std::map` to store JSON objects, and thus stores object keys **sorted alphabetically**.
??? example
```cpp
#include <iostream>
#include "json.hpp"
using json = nlohmann::json;
int main()
{
json j;
j["one"] = 1;
j["two"] = 2;
j["three"] = 3;
std::cout << j.dump(2) << '\n';
}
```
Output:
```json
{
"one": 1,
"three": 3,
"two": 2
}
```
If you do want to preserve the **insertion order**, you can try the type [`nlohmann::ordered_json`](https://github.com/nlohmann/json/issues/2179).
??? example
```cpp
#include <iostream>
#include <nlohmann/json.hpp>
using ordered_json = nlohmann::ordered_json;
int main()
{
ordered_json j;
j["one"] = 1;
j["two"] = 2;
j["three"] = 3;
std::cout << j.dump(2) << '\n';
}
```
Output:
```json
{
"one": 1,
"two": 2,
"three": 3
}
```
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)).
......@@ -14,6 +14,7 @@ interface json::sax_t {
+ {abstract} bool number_float(number_float_t val, const string_t& s)
+ {abstract} bool string(string_t& val)
+ {abstract} bool binary(binary_t& val)
+ {abstract} bool start_object(std::size_t elements)
+ {abstract} bool end_object()
......@@ -41,6 +42,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
bool string(string_t& val);
// called when a binary value is parsed; value is passed and can be safely moved away
bool binary(binary& val);
// 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);
......
......@@ -32,6 +32,24 @@ Exceptions are used widely within the library. They can, however, be switched of
Note that `JSON_THROW_USER` should leave the current scope (e.g., by throwing or aborting), as continuing after it may yield undefined behavior.
??? example
The code below switches off exceptions and creates a log entry with a detailed error message in case of errors.
```cpp
#include <iostream>
#define JSON_TRY_USER if(true)
#define JSON_CATCH_USER(exception) if(false)
#define JSON_THROW_USER(exception) \
{std::clog << "Error in " << __FILE__ << ":" << __LINE__ \
<< " (function " << __FUNCTION__ << ") - " \
<< (exception).what() << std::endl; \
std::abort();}
#include <nlohmann/json.hpp>
```
## Parse errors
This exception is thrown by the library when a parse error occurs. Parse errors
......@@ -261,6 +279,16 @@ The parsing of the corresponding BSON record type is not implemented (yet).
[json.exception.parse_error.114] parse error at byte 5: Unsupported BSON record type 0xFF
```
### json.exception.parse_error.115
A UBJSON high-precision number could not be parsed.
!!! failure "Example message"
```
[json.exception.parse_error.115] parse error at byte 5: syntax error while parsing UBJSON high-precision number: invalid number text: 1A
```
## Iterator errors
This exception is thrown if iterators passed to a library function do not match
......@@ -747,6 +775,10 @@ UBJSON and BSON only support integer numbers up to 9223372036854775807.
number overflow serializing '9223372036854775808'
```
!!! note
Since version 3.9.0, integer numbers beyond int64 are serialized as high-precision UBJSON numbers, and this exception does not further occur.
### json.exception.out_of_range.408
The size (following `#`) of an UBJSON array or object exceeds the maximal capacity.
......
......@@ -2,31 +2,6 @@
## Limitations
### Comments
!!! question "Questions"
- Why does the library not support comments?
- Can you add support for JSON5/JSONC/HOCON so that comments are supported?
This library does not support comments. 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.
2. This was not an oversight: Douglas Crockford [wrote on this](https://plus.google.com/118095276221607585885/posts/RK8qyGVaGSr) in May 2012:
> I removed comments from JSON because I saw people were using them to hold parsing directives, a practice which would have destroyed interoperability. I know that the lack of comments makes some people sad, but it shouldn't.
> Suppose you are using JSON to keep configuration files, which you would like to annotate. Go ahead and insert all the comments you like. Then pipe it through JSMin before handing it to your JSON parser.
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:
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).
### Relaxed parsing
!!! question
......@@ -69,18 +44,6 @@ No, this is not possible. See <https://github.com/nlohmann/json/issues/932> for
## Serialization issues
### Order of object keys
!!! question "Questions"
- Why are object keys sorted?
- Why is the insertion order of object keys not preserved?
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)).
### Number precision
!!! question
......
......@@ -4,7 +4,7 @@
The class is licensed under the [MIT License](http://opensource.org/licenses/MIT):
Copyright &copy; 2013-2019 [Niels Lohmann](http://nlohmann.me)
Copyright &copy; 2013-2020 [Niels Lohmann](http://nlohmann.me)
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
......
......@@ -3,5 +3,8 @@ import os.path
def copy_doxygen(*args, **kwargs):
shutil.copytree('../html', os.path.join(kwargs['config']['site_dir'], 'doxygen'))
print('Copy Doxygen complete')
doxygen_dir = os.path.join(kwargs['config']['site_dir'], 'doxygen')
if not os.path.isdir(doxygen_dir) or not os.listdir(doxygen_dir):
print('Copy Doxygen files...')
shutil.copytree('../html', doxygen_dir)
print('Copy Doxygen complete')
......@@ -44,16 +44,24 @@ nav:
- features/binary_formats/messagepack.md
- features/binary_formats/ubjson.md
- features/binary_values.md
- features/comments.md
- Element Access:
- features/element_access/index.md
- features/element_access/unchecked_access.md
- features/element_access/checked_access.md
- features/element_access/default_value.md
- features/iterators.md
- features/json_pointer.md
- features/json_patch.md
- features/merge_patch.md
- features/enum_conversion.md
- features/object_order.md
- Parsing:
- features/parsing/index.md
- features/parsing/parse_exceptions.md
- features/parsing/parser_callbacks.md
- features/parsing/sax_interface.md
- features/parsing/index.md
- features/parsing/parse_exceptions.md
- features/parsing/parser_callbacks.md
- features/parsing/sax_interface.md
- features/enum_conversion.md
- features/macros.md
- features/types.md
- Integration:
- integration/index.md
......@@ -61,6 +69,12 @@ nav:
- integration/package_managers.md
- Doxygen:
- doxygen/index.html
- API:
- basic_json:
- api/basic_json/index.md
- api/basic_json/dump.md
- api/basic_json/meta.md
- api/basic_json/parse.md
# Extras
extra:
......@@ -79,6 +93,7 @@ extra:
# Extensions
markdown_extensions:
- admonition
- def_list
- codehilite:
guess_lang: false
- toc:
......
......@@ -37,7 +37,7 @@ struct adl_serializer
@param[in,out] j JSON value to write to
@param[in] val value to read from
*/
template <typename BasicJsonType, typename ValueType>
template<typename BasicJsonType, typename ValueType>
static auto to_json(BasicJsonType& j, ValueType&& val) noexcept(
noexcept(::nlohmann::to_json(j, std::forward<ValueType>(val))))
-> decltype(::nlohmann::to_json(j, std::forward<ValueType>(val)), void())
......
#pragma once
// Header <ciso646> is removed in C++20.
// See <https://github.com/nlohmann/json/issues/2089> for more information.
#if __cplusplus <= 201703L
#include <ciso646> // and, not, or
#endif
......@@ -9,7 +9,6 @@
#include <valarray> // valarray
#include <vector> // vector
#include <nlohmann/detail/boolean_operators.hpp>
#include <nlohmann/detail/iterators/iteration_proxy.hpp>
#include <nlohmann/detail/meta/cpp_future.hpp>
#include <nlohmann/detail/meta/type_traits.hpp>
......@@ -56,9 +55,9 @@ struct external_constructor<value_t::string>
j.assert_invariant();
}
template<typename BasicJsonType, typename CompatibleStringType,
enable_if_t<not std::is_same<CompatibleStringType, typename BasicJsonType::string_t>::value,
int> = 0>
template < typename BasicJsonType, typename CompatibleStringType,
enable_if_t < !std::is_same<CompatibleStringType, typename BasicJsonType::string_t>::value,
int > = 0 >
static void construct(BasicJsonType& j, const CompatibleStringType& str)
{
j.m_type = value_t::string;
......@@ -144,9 +143,9 @@ struct external_constructor<value_t::array>
j.assert_invariant();
}
template<typename BasicJsonType, typename CompatibleArrayType,
enable_if_t<not std::is_same<CompatibleArrayType, typename BasicJsonType::array_t>::value,
int> = 0>
template < typename BasicJsonType, typename CompatibleArrayType,
enable_if_t < !std::is_same<CompatibleArrayType, typename BasicJsonType::array_t>::value,
int > = 0 >
static void construct(BasicJsonType& j, const CompatibleArrayType& arr)
{
using std::begin;
......@@ -203,8 +202,8 @@ struct external_constructor<value_t::object>
j.assert_invariant();
}
template<typename BasicJsonType, typename CompatibleObjectType,
enable_if_t<not std::is_same<CompatibleObjectType, typename BasicJsonType::object_t>::value, int> = 0>
template < typename BasicJsonType, typename CompatibleObjectType,
enable_if_t < !std::is_same<CompatibleObjectType, typename BasicJsonType::object_t>::value, int > = 0 >
static void construct(BasicJsonType& j, const CompatibleObjectType& obj)
{
using std::begin;
......@@ -275,20 +274,20 @@ void to_json(BasicJsonType& j, const std::vector<bool>& e)
external_constructor<value_t::array>::construct(j, e);
}
template <typename BasicJsonType, typename CompatibleArrayType,
enable_if_t<is_compatible_array_type<BasicJsonType,
CompatibleArrayType>::value and
not is_compatible_object_type<BasicJsonType, CompatibleArrayType>::value and
not is_compatible_string_type<BasicJsonType, CompatibleArrayType>::value and
not std::is_same<typename BasicJsonType::binary_t, CompatibleArrayType>::value and
not is_basic_json<CompatibleArrayType>::value,
int> = 0>
template < typename BasicJsonType, typename CompatibleArrayType,
enable_if_t < is_compatible_array_type<BasicJsonType,
CompatibleArrayType>::value&&
!is_compatible_object_type<BasicJsonType, CompatibleArrayType>::value&&
!is_compatible_string_type<BasicJsonType, CompatibleArrayType>::value&&
!std::is_same<typename BasicJsonType::binary_t, CompatibleArrayType>::value&&
!is_basic_json<CompatibleArrayType>::value,
int > = 0 >
void to_json(BasicJsonType& j, const CompatibleArrayType& arr)
{
external_constructor<value_t::array>::construct(j, arr);
}
template <typename BasicJsonType>
template<typename BasicJsonType>
void to_json(BasicJsonType& j, const typename BasicJsonType::binary_t& bin)
{
external_constructor<value_t::binary>::construct(j, bin);
......@@ -307,8 +306,8 @@ void to_json(BasicJsonType& j, typename BasicJsonType::array_t&& arr)
external_constructor<value_t::array>::construct(j, std::move(arr));
}
template<typename BasicJsonType, typename CompatibleObjectType,
enable_if_t<is_compatible_object_type<BasicJsonType, CompatibleObjectType>::value and not is_basic_json<CompatibleObjectType>::value, int> = 0>
template < typename BasicJsonType, typename CompatibleObjectType,
enable_if_t < is_compatible_object_type<BasicJsonType, CompatibleObjectType>::value&& !is_basic_json<CompatibleObjectType>::value, int > = 0 >
void to_json(BasicJsonType& j, const CompatibleObjectType& obj)
{
external_constructor<value_t::object>::construct(j, obj);
......@@ -322,9 +321,9 @@ void to_json(BasicJsonType& j, typename BasicJsonType::object_t&& obj)
template <
typename BasicJsonType, typename T, std::size_t N,
enable_if_t<not std::is_constructible<typename BasicJsonType::string_t,
const T(&)[N]>::value,
int> = 0 >
enable_if_t < !std::is_constructible<typename BasicJsonType::string_t,
const T(&)[N]>::value,
int > = 0 >
void to_json(BasicJsonType& j, const T(&arr)[N])
{
external_constructor<value_t::array>::construct(j, arr);
......@@ -337,8 +336,8 @@ void to_json(BasicJsonType& j, const std::pair<T1, T2>& p)
}
// for https://github.com/nlohmann/json/pull/1134
template < typename BasicJsonType, typename T,
enable_if_t<std::is_same<T, iteration_proxy_value<typename BasicJsonType::iterator>>::value, int> = 0>
template<typename BasicJsonType, typename T,
enable_if_t<std::is_same<T, iteration_proxy_value<typename BasicJsonType::iterator>>::value, int> = 0>
void to_json(BasicJsonType& j, const T& b)
{
j = { {b.key(), b.value()} };
......
......@@ -97,6 +97,7 @@ json.exception.parse_error.110 | parse error at 1: cannot read 2 bytes from vect
json.exception.parse_error.112 | parse error at 1: error reading CBOR; last byte: 0xF8 | Not all types of CBOR or MessagePack are supported. This exception occurs if an unsupported byte was read.
json.exception.parse_error.113 | parse error at 2: expected a CBOR string; last byte: 0x98 | While parsing a map key, a value that is not a string has been read.
json.exception.parse_error.114 | parse error: Unsupported BSON record type 0x0F | The parsing of the corresponding BSON record type is not implemented (yet).
json.exception.parse_error.115 | parse error at byte 5: syntax error while parsing UBJSON high-precision number: invalid number text: 1A | A UBJSON high-precision number could not be parsed.
@note For an input with n bytes, 1 is the index of the first character and n+1
is the index of the terminating null byte or the end of file. This also
......@@ -285,7 +286,7 @@ json.exception.out_of_range.403 | key 'foo' not found | The provided key was not
json.exception.out_of_range.404 | unresolved reference token 'foo' | A reference token in a JSON Pointer could not be resolved.
json.exception.out_of_range.405 | JSON pointer has no parent | The JSON Patch operations 'remove' and 'add' can not be applied to the root element of the JSON value.
json.exception.out_of_range.406 | number overflow parsing '10E1000' | A parsed number could not be stored as without changing it to NaN or INF.
json.exception.out_of_range.407 | number overflow serializing '9223372036854775808' | UBJSON and BSON only support integer numbers up to 9223372036854775807. |
json.exception.out_of_range.407 | number overflow serializing '9223372036854775808' | UBJSON and BSON only support integer numbers up to 9223372036854775807. (until version 3.8.0) |
json.exception.out_of_range.408 | excessive array size: 8658170730974374167 | The size (following `#`) of an UBJSON array or object exceeds the maximal capacity. |
json.exception.out_of_range.409 | BSON key cannot contain code point U+0000 (at byte 2) | Key identifiers to be serialized to BSON cannot contain code point U+0000, since the key is stored as zero-terminated c-string |
......
#pragma once
#include <cstddef> // size_t, uint8_t
#include <functional> // hash
namespace nlohmann
{
namespace detail
{
// boost::hash_combine
inline std::size_t combine(std::size_t seed, std::size_t h) noexcept
{
seed ^= h + 0x9e3779b9 + (seed << 6U) + (seed >> 2U);
return seed;
}
/*!
@brief hash a JSON value
The hash function tries to rely on std::hash where possible. Furthermore, the
type of the JSON value is taken into account to have different hash values for
null, 0, 0U, and false, etc.
@tparam BasicJsonType basic_json specialization
@param j JSON value to hash
@return hash value of j
*/
template<typename BasicJsonType>
std::size_t hash(const BasicJsonType& j)
{
using string_t = typename BasicJsonType::string_t;
using number_integer_t = typename BasicJsonType::number_integer_t;
using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
using number_float_t = typename BasicJsonType::number_float_t;
const auto type = static_cast<std::size_t>(j.type());
switch (j.type())
{
case BasicJsonType::value_t::null:
case BasicJsonType::value_t::discarded:
{
return combine(type, 0);
}
case BasicJsonType::value_t::object:
{
auto seed = combine(type, j.size());
for (const auto& element : j.items())
{
const auto h = std::hash<string_t> {}(element.key());
seed = combine(seed, h);
seed = combine(seed, hash(element.value()));
}
return seed;
}
case BasicJsonType::value_t::array:
{
auto seed = combine(type, j.size());
for (const auto& element : j)
{
seed = combine(seed, hash(element));
}
return seed;
}
case BasicJsonType::value_t::string:
{
const auto h = std::hash<string_t> {}(j.template get_ref<const string_t&>());
return combine(type, h);
}
case BasicJsonType::value_t::boolean:
{
const auto h = std::hash<bool> {}(j.template get<bool>());
return combine(type, h);
}
case BasicJsonType::value_t::number_integer:
{
const auto h = std::hash<number_integer_t> {}(j.template get<number_integer_t>());
return combine(type, h);
}
case nlohmann::detail::value_t::number_unsigned:
{
const auto h = std::hash<number_unsigned_t> {}(j.template get<number_unsigned_t>());
return combine(type, h);
}
case nlohmann::detail::value_t::number_float:
{
const auto h = std::hash<number_float_t> {}(j.template get<number_float_t>());
return combine(type, h);
}
case nlohmann::detail::value_t::binary:
{
auto seed = combine(type, j.get_binary().size());
const auto h = std::hash<bool> {}(j.get_binary().has_subtype());
seed = combine(seed, h);
seed = combine(seed, j.get_binary().subtype());
for (const auto byte : j.get_binary())
{
seed = combine(seed, std::hash<std::uint8_t> {}(byte));
}
return seed;
}
default: // LCOV_EXCL_LINE
JSON_ASSERT(false); // LCOV_EXCL_LINE
}
}
} // namespace detail
} // namespace nlohmann
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
......@@ -18,8 +18,6 @@ template<typename BasicJsonType> struct internal_iterator
typename BasicJsonType::object_t::iterator object_iterator {};
/// iterator for JSON arrays
typename BasicJsonType::array_t::iterator array_iterator {};
/// iterator for JSON binary arrays
typename BasicJsonType::binary_t::container_type::iterator binary_iterator {};
/// generic iterator for all other types
primitive_iterator_t primitive_iterator {};
};
......
......@@ -15,9 +15,11 @@ namespace detail
template<typename string_type>
void int_to_string( string_type& target, std::size_t value )
{
target = std::to_string(value);
// For ADL
using std::to_string;
target = to_string(value);
}
template <typename IteratorType> class iteration_proxy_value
template<typename IteratorType> class iteration_proxy_value
{
public:
using difference_type = std::ptrdiff_t;
......@@ -72,7 +74,7 @@ template <typename IteratorType> class iteration_proxy_value
/// return key of the iterator
const string_type& key() const
{
assert(anchor.m_object != nullptr);
JSON_ASSERT(anchor.m_object != nullptr);
switch (anchor.m_object->type())
{
......@@ -131,7 +133,7 @@ template<typename IteratorType> class iteration_proxy
// Structured Bindings Support
// For further reference see https://blog.tartanllama.xyz/structured-bindings/
// And see https://github.com/nlohmann/json/pull/1391
template <std::size_t N, typename IteratorType, enable_if_t<N == 0, int> = 0>
template<std::size_t N, typename IteratorType, enable_if_t<N == 0, int> = 0>
auto get(const nlohmann::detail::iteration_proxy_value<IteratorType>& i) -> decltype(i.key())
{
return i.key();
......@@ -139,7 +141,7 @@ auto get(const nlohmann::detail::iteration_proxy_value<IteratorType>& i) -> decl
// Structured Bindings Support
// For further reference see https://blog.tartanllama.xyz/structured-bindings/
// And see https://github.com/nlohmann/json/pull/1391
template <std::size_t N, typename IteratorType, enable_if_t<N == 1, int> = 0>
template<std::size_t N, typename IteratorType, enable_if_t<N == 1, int> = 0>
auto get(const nlohmann::detail::iteration_proxy_value<IteratorType>& i) -> decltype(i.value())
{
return i.value();
......@@ -158,11 +160,11 @@ namespace std
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wmismatched-tags"
#endif
template <typename IteratorType>
template<typename IteratorType>
class tuple_size<::nlohmann::detail::iteration_proxy_value<IteratorType>>
: public std::integral_constant<std::size_t, 2> {};
template <std::size_t N, typename IteratorType>
template<std::size_t N, typename IteratorType>
class tuple_element<N, ::nlohmann::detail::iteration_proxy_value<IteratorType >>
{
public:
......
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment