Skip to content

Optional comment support. #363

@qis

Description

@qis

Here are two basic_json functions that allow parsing JSON input with comments. This implementation is not very efficient and I would love to see this functionality implemented (either this way or properly) in nlohmann/json.

    /*!
    @copydoc parse(std::istream&, parser_callback_t)
    */
    static basic_json parse_relaxed(std::istream& i, parser_callback_t cb = nullptr)
    {
        std::stringstream ss;
        for (std::string line; std::getline(i, line);) {
            enum class state { none, escape, escape_u, escape_0, escape_1, escape_2, string, slash, end };
            state s = state::none;
            std::size_t size = 0;
            for (auto it = line.begin(), end = line.end(); s != state::end && it != end; ++it) {
                switch (s) {
                case state::none:
                    switch (*it) {
                    case '"': s = state::string; break;
                    case '/': s = state::slash; break;
                    }
                    break;
                case state::string:
                    switch (*it) {
                    case '"': s = state::none; break;
                    case '\\': s = state::escape; break;
                    }
                    break;
                case state::escape:
                    switch (*it) {
                    case 'u': s = state::escape_u; break;
                    default: s = state::string; break;
                    }
                    break;
                case state::escape_u:
                case state::escape_0:
                case state::escape_1:
                case state::escape_2:
                    if (*it < '0' || *it > '9') {
                        throw std::domain_error("invalid unicode escape sequence");
                    }
                    s = static_cast<state>(static_cast<int>(s) + 1);
                    break;
                case state::slash:
                    if (*it != '/') {
                        throw std::domain_error("invalid comment syntax");
                    }
                    size--;
                    s = state::end;
                    continue;
                case state::end:
                    break;
                }
                size++;
            }
            ss.write(line.data(), size);
        }
        return parse(ss, cb);
    }

    /*!
    @copydoc parse_relaxed(std::istream&, parser_callback_t)
    */
    static basic_json parse_relaxed(const string_t& s, parser_callback_t cb = nullptr)
    {
        return parse_relaxed(std::istringstream(s), cb);
    }

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions