I looked at a quick parser [*] based on http://www.ietf.org/rfc/rfc4627.txt using Spirit Qi.
It is not actually parsed in the AST, but it parses the entire JSON payload, which is actually a little more than what is required here.
(http://liveworkspace.org/code/3k4Yor$2):
Non-JSON part of input starts after valid JSON: ', "some more stuff")'
, 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";
JSON ( ).
:
- Iterator, , , Qt (?)
- ,
qi::space qi::blank - (. TODO), (. ).
[*] , -, - . , :)
:
namespace qi = boost::spirit::qi;
template <typename It, typename Skipper = qi::space_type>
struct parser : qi::grammar<It, Skipper>
{
parser() : parser::base_type(json)
{
value = qi::lit("false") | "null" | "true" | object | array | number | string;
object = '{' >> -(member % ',') >> '}';
member = string >> ':' >> value;
array = '[' >> -(value % ',') >> ']';
number = qi::double_;
string = qi::lexeme [ '"' >> *char_ >> '"' ];
static const qi::uint_parser<uint32_t, 16, 4, 4> _4HEXDIG;
char_ = ~qi::char_("\"\\") |
qi::char_("\x5C") >> (
qi::char_("\x22") |
qi::char_("\x5C") |
qi::char_("\x2F") |
qi::char_("\x62") |
qi::char_("\x66") |
qi::char_("\x6E") |
qi::char_("\x72") |
qi::char_("\x74") |
qi::char_("\x75") >> _4HEXDIG )
;
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)
{
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)
{
std::string frag(e.first, e.last);
std::cerr << e.what() << "'" << frag << "'\n";
return false;
}
}
int main()
{
std::cin.unsetf(std::ios::skipws);
std::istream_iterator<char> it(std::cin), pte;
const std::string input(it, pte);
auto f(begin(input)), l(end(input));
const std::string input("foo([1, 2, 3], \"some more stuff\")");
auto f(begin(input)), l(end(input));
std::advance(f, 4);
bool ok = tryParseAsJson(f, l);
if (ok)
std::cout << "Non-JSON part of input starts after valid JSON: '" << std::string(f, l) << "'\n";
return ok? 0 : 255;
}