使用QJsonDocument将子字符串解析为JSON

lee*_*mes 5 c++ qt parsing json qt5

我有一个字符串包含(未IS)JSON编码的数据,像在本例中:

foo([1, 2, 3], "some more stuff")
    |        |
  start     end   (of JSON-encoded data)
Run Code Online (Sandbox Code Playgroud)

我们在应用程序中使用的完整语言嵌套了JSON编码的数据,而其他语言则是微不足道的(只是递归的东西).在递归解析器中从左到右解析这样的字符串时,我知道当我遇到JSON编码的值时,就像这里[1, 2, 3]从索引4开始.解析这个子字符串后,我需要知道结束位置以继续解析其余的的字符串.

我想将这个子字符串传递给QJsonDocumentQt5中经过良好测试的JSON解析器.但是在阅读文档时,不可能仅将子字符串解析为JSON,这意味着只要解析的数据结束(在使用]此处之后)控制返回而​​不报告解析错误.此外,我需要知道结束位置继续解析我自己的东西(这里剩下的字符串是, "some more stuff")).

为此,我曾经使用自定义JSON解析器,它通过引用获取当前位置并在完成解析后更新它.但由于它是业务应用程序的安全关键部分,我们不想再坚持使用我自己设计的解析器了.我的意思是QJsonDocument,所以为什么不使用它.(我们已经使用Qt5了.)

作为一种解决方法,我正在考虑这种方法:

  • QJsonDocument解析从当前位置开始的子字符串(这是无效的JSON)
  • 错误报告了一个意外的字符,这是JSON之外的一些位置
  • 让我们QJsonDocument再次解析,但这次子串具有正确的结束位置

第二个想法是编写一个"JSON端扫描器",它接受整个字符串,一个起始位置并返回JSON编码数据的结束位置.这也需要解析,因为不匹配的括号/括号可以出现在字符串值中,但与完全手工制作的JSON解析器相比,编写(和使用)这样的类应该更容易(也更安全).

有没有人有更好的主意?

seh*_*ehe 4

我使用 Spirit Qi 基于http://www.ietf.org/rfc/rfc4627.txt推出了一个快速解析器[*] 。

它实际上并没有解析为 AST,但它解析了所有 JSON 有效负载,这实际上比此处所需的要多一些。

这里的示例(http://liveworkspace.org/code/3k4Yor$2)输出:

Non-JSON part of input starts after valid JSON: ', "some more stuff")'
Run Code Online (Sandbox Code Playgroud)

根据OP给出的测试:

const std::string input("foo([1, 2, 3], \"some more stuff\")");

// set to start of JSON
auto f(begin(input)), l(end(input));
std::advance(f, 4);

bool ok = doParse(f, l); // updates f to point after the start of valid JSON

if (ok) 
    std::cout << "Non-JSON part of input starts after valid JSON: '" << std::string(f, l) << "'\n";
Run Code Online (Sandbox Code Playgroud)

我已经测试了其他几个涉及更多的 JSON 文档(包括多行)。

几点说明:

  • 我制作了基于迭代器的解析器,因此它可能很容易与 Qt 字符串一起工作(?)
  • 如果您想禁止多行片段,请将船长从更改qi::spaceqi::blank
  • 有一个关于数字解析的一致性快捷方式(请参阅 TODO),它不会影响此答案的有效性(请参阅评论)。

[*] 从技术上讲,这更像是一个解析器存根,因为它不会转换成其他东西。它基本上是一个词法分析器承担了太多的工作:)


示例完整代码:

// #define BOOST_SPIRIT_DEBUG
#include <boost/spirit/include/qi.hpp>

namespace qi = boost::spirit::qi;

template <typename It, typename Skipper = qi::space_type>
    struct parser : qi::grammar<It, Skipper>
{
    parser() : parser::base_type(json)
    {
        // 2.1 values
        value = qi::lit("false") | "null" | "true" | object | array | number | string;

        // 2.2 objects
        object = '{' >> -(member % ',') >> '}';
        member = string >> ':' >> value;

        // 2.3 Arrays
        array = '[' >> -(value % ',') >> ']';

        // 2.4.  Numbers
        // Note out spirit grammar takes a shortcut, as the RFC specification is more restrictive:
        //
        // However non of the above affect any structure characters (:,{}[] and double quotes) so it doesn't
        // matter for the current purpose. For full compliance, this remains TODO:
        //
        //    Numeric values that cannot be represented as sequences of digits
        //    (such as Infinity and NaN) are not permitted.
        //     number = [ minus ] int [ frac ] [ exp ]
        //     decimal-point = %x2E       ; .
        //     digit1-9 = %x31-39         ; 1-9
        //     e = %x65 / %x45            ; e E
        //     exp = e [ minus / plus ] 1*DIGIT
        //     frac = decimal-point 1*DIGIT
        //     int = zero / ( digit1-9 *DIGIT )
        //     minus = %x2D               ; -
        //     plus = %x2B                ; +
        //     zero = %x30                ; 0
        number = qi::double_; // shortcut :)

        // 2.5 Strings
        string = qi::lexeme [ '"' >> *char_ >> '"' ];

        static const qi::uint_parser<uint32_t, 16, 4, 4> _4HEXDIG;

        char_ = ~qi::char_("\"\\") |
               qi::char_("\x5C") >> (       // \ (reverse solidus)
                   qi::char_("\x22") |      // "    quotation mark  U+0022
                   qi::char_("\x5C") |      // \    reverse solidus U+005C
                   qi::char_("\x2F") |      // /    solidus         U+002F
                   qi::char_("\x62") |      // b    backspace       U+0008
                   qi::char_("\x66") |      // f    form feed       U+000C
                   qi::char_("\x6E") |      // n    line feed       U+000A
                   qi::char_("\x72") |      // r    carriage return U+000D
                   qi::char_("\x74") |      // t    tab             U+0009
                   qi::char_("\x75") >> _4HEXDIG )  // uXXXX                U+XXXX
               ;

        // entry point
        json = value;

        BOOST_SPIRIT_DEBUG_NODES(
                (json)(value)(object)(member)(array)(number)(string)(char_));
    }

  private:
    qi::rule<It, Skipper> json, value, object, member, array, number, string;
    qi::rule<It> char_;
};

template <typename It>
bool tryParseAsJson(It& f, It l) // note: first iterator gets updated
{
    static const parser<It, qi::space_type> p;

    try
    {
        return qi::phrase_parse(f,l,p,qi::space);
    } catch(const qi::expectation_failure<It>& e)
    {
        // expectation points not currently used, but we could tidy up the grammar to bail on unexpected tokens
        std::string frag(e.first, e.last);
        std::cerr << e.what() << "'" << frag << "'\n";
        return false;
    }
}

int main()
{
#if 0
    // read full stdin
    std::cin.unsetf(std::ios::skipws);
    std::istream_iterator<char> it(std::cin), pte;
    const std::string input(it, pte);

    // set up parse iterators
    auto f(begin(input)), l(end(input));
#else
    const std::string input("foo([1, 2, 3], \"some more stuff\")");

    // set to start of JSON
    auto f(begin(input)), l(end(input));
    std::advance(f, 4);
#endif

    bool ok = tryParseAsJson(f, l); // updates f to point after the end of valid JSON

    if (ok) 
        std::cout << "Non-JSON part of input starts after valid JSON: '" << std::string(f, l) << "'\n";
    return ok? 0 : 255;
}
Run Code Online (Sandbox Code Playgroud)

  • 出于好奇,我决定让 JSON 解析器 [UNICODE 感知](https://raw.github.com/sehe/spirit-v2-json/master/testcases/test1.json) 并解析为实际的 AST 树 ([如果我自己可以这么说的话,那就太美了](https://github.com/sehe/spirit-v2-json/blob/master/JSON.hpp))。往返测试检查(尽管顺序不稳定,因此第一个测试报告漏报;使用“list&lt;pair&lt;K,V&gt;&gt;”而不是“map&lt;K,V&gt;”来防止这种情况)。参见[我的github](https://github.com/sehe/spirit-v2-json) (4认同)