Skip to content

# basic_json::parse

    // (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`
  a compatible iterator type

## 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, `true` by default)
`ignore_comments` (in)
  whether comments should be ignored and treated like whitespace (`true`) or yield a parse error (`false`); (optional, `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 `false`, the return value will be `value_t::discarded`. The latter can be checked with `is_discarded`.

## Exception safety

Strong guarantee: if an exception is thrown, there are no changes in the JSON value.

## 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

Parsing from a charater array

The example below demonstrates the `parse()` function reading from an array.

    #include <iostream>
    #include <iomanip>
    #include <nlohmann/json.hpp>

    using json = nlohmann::json;

    int main()
    {
        // a JSON text
        char text[] = R"(
        {
            "Image": {
                "Width":  800,
                "Height": 600,
                "Title":  "View from 15th Floor",
                "Thumbnail": {
                    "Url":    "http://www.example.com/image/481989943",
                    "Height": 125,
                    "Width":  100
                },
                "Animated" : false,
                "IDs": [116, 943, 234, 38793]
            }
        }
        )";

        // parse and serialize JSON
        json j_complete = json::parse(text);
        std::cout << std::setw(4) << j_complete << "\n\n";
    }

Output:

    {
        "Image": {
            "Animated": false,
            "Height": 600,
            "IDs": [
                116,
                943,
                234,
                38793
            ],
            "Thumbnail": {
                "Height": 125,
                "Url": "http://www.example.com/image/481989943",
                "Width": 100
            },
            "Title": "View from 15th Floor",
            "Width": 800
        }
    }

Parsing from a string

The example below demonstrates the `parse()` function with and without callback function.

    #include <iostream>
    #include <iomanip>
    #include <nlohmann/json.hpp>

    using json = nlohmann::json;

    int main()
    {
        // a JSON text
        auto text = R"(
        {
            "Image": {
                "Width":  800,
                "Height": 600,
                "Title":  "View from 15th Floor",
                "Thumbnail": {
                    "Url":    "http://www.example.com/image/481989943",
                    "Height": 125,
                    "Width":  100
                },
                "Animated" : false,
                "IDs": [116, 943, 234, 38793]
            }
        }
        )";

        // parse and serialize JSON
        json j_complete = json::parse(text);
        std::cout << std::setw(4) << j_complete << "\n\n";

        // define parser callback
        json::parser_callback_t cb = [](int depth, json::parse_event_t event, json & parsed)
        {
            // skip object elements with key "Thumbnail"
            if (event == json::parse_event_t::key and parsed == json("Thumbnail"))
            {
                return false;
            }
            else
            {
                return true;
            }
        };

        // parse (with callback) and serialize JSON
        json j_filtered = json::parse(text, cb);
        std::cout << std::setw(4) << j_filtered << '\n';
    }

Output:

    {
        "Image": {
            "Animated": false,
            "Height": 600,
            "IDs": [
                116,
                943,
                234,
                38793
            ],
            "Thumbnail": {
                "Height": 125,
                "Url": "http://www.example.com/image/481989943",
                "Width": 100
            },
            "Title": "View from 15th Floor",
            "Width": 800
        }
    }

    {
        "Image": {
            "Animated": false,
            "Height": 600,
            "IDs": [
                116,
                943,
                234,
                38793
            ],
            "Title": "View from 15th Floor",
            "Width": 800
        }
    }

Parsing from an input stream

The example below demonstrates the `parse()` function with and without callback function.

    #include <iostream>
    #include <iomanip>
    #include <sstream>
    #include <nlohmann/json.hpp>

    using json = nlohmann::json;

    int main()
    {
        // a JSON text
        auto text = R"(
        {
            "Image": {
                "Width":  800,
                "Height": 600,
                "Title":  "View from 15th Floor",
                "Thumbnail": {
                    "Url":    "http://www.example.com/image/481989943",
                    "Height": 125,
                    "Width":  100
                },
                "Animated" : false,
                "IDs": [116, 943, 234, 38793]
            }
        }
        )";

        // fill a stream with JSON text
        std::stringstream ss;
        ss << text;

        // parse and serialize JSON
        json j_complete = json::parse(ss);
        std::cout << std::setw(4) << j_complete << "\n\n";

        // define parser callback
        json::parser_callback_t cb = [](int depth, json::parse_event_t event, json & parsed)
        {
            // skip object elements with key "Thumbnail"
            if (event == json::parse_event_t::key and parsed == json("Thumbnail"))
            {
                return false;
            }
            else
            {
                return true;
            }
        };

        // fill a stream with JSON text
        ss.clear();
        ss << text;

        // parse (with callback) and serialize JSON
        json j_filtered = json::parse(ss, cb);
        std::cout << std::setw(4) << j_filtered << '\n';
    }

Output:

    {
        "Image": {
            "Animated": false,
            "Height": 600,
            "IDs": [
                116,
                943,
                234,
                38793
            ],
            "Thumbnail": {
                "Height": 125,
                "Url": "http://www.example.com/image/481989943",
                "Width": 100
            },
            "Title": "View from 15th Floor",
            "Width": 800
        }
    }

    {
        "Image": {
            "Animated": false,
            "Height": 600,
            "IDs": [
                116,
                943,
                234,
                38793
            ],
            "Title": "View from 15th Floor",
            "Width": 800
        }
    }

Parsing from a contiguous container

The example below demonstrates the `parse()` function reading from a contiguous container.

    #include <iostream>
    #include <iomanip>
    #include <nlohmann/json.hpp>

    using json = nlohmann::json;

    int main()
    {
        // a JSON text given as std::vector
        std::vector<uint8_t> text = {'[', '1', ',', '2', ',', '3', ']', '\0'};

        // parse and serialize JSON
        json j_complete = json::parse(text);
        std::cout << std::setw(4) << j_complete << "\n\n";
    }

Output:

    [
        1,
        2,
        3
    ]

Effect of `allow_exceptions` parameter

The example below demonstrates the effect of the `allow_exceptions` parameter in the ´parse()` function.

    #include <iostream>
    #include <nlohmann/json.hpp>

    using json = nlohmann::json;

    int main()
    {
        // an invalid JSON text
        std::string text = R"(
        {
            "key": "value without closing quotes
        }
        )";

        // parse with exceptions
        try
        {
            json j = json::parse(text);
        }
        catch (json::parse_error& e)
        {
            std::cout << e.what() << std::endl;
        }

        // parse without exceptions
        json j = json::parse(text, nullptr, false);

        if (j.is_discarded())
        {
            std::cout << "the input is invalid JSON" << std::endl;
        }
        else
        {
            std::cout << "the input is valid JSON: " << j << std::endl;
        }
    }

Output:

    [json.exception.parse_error.101] parse error at line 4, column 0: syntax error while parsing value - invalid string: control character U+000A (LF) must be escaped to \u000A or \n; last read: '"value without closing quotes<U+000A>'
    the input is invalid JSON

## Version history

- Added in version 1.0.0.
- Overload for contiguous containers (1) added in version 2.0.3.
- Ignoring comments via `ignore_comments` added in version 3.9.0.