1

I'm new to boost library and I really need some help. In my case, I need to use boost lib to parse an external JSON file with comments(eg. "//" symbol). I use the following code to parse the unformatted json.

boost::property_tree::ptree root;
boost::property_tree::read_json<boost::property_tree::ptree>(file_path,root);

It fails since the json file is not a standard file. I also noticed the reference in Are comments allowed in a JSON file for boost read_json?. However. I still use this unformatted file for my case.

My question is whether there is a 'ignore_comments' like nlohmann lib in boost lib or not. How I can handle this issue under the condition of boost lib.

terry
  • 11
  • 2

1 Answers1

3

There is an option to allow non-standard behaviour for the boost.json.parser:

https://www.boost.org/doc/libs/develop/libs/json/doc/html/json/input_output.html#json.input_output.parsing.non_standard_json

parse_options opt;                                  // all extensions default to off
opt.allow_comments = true;                          // permit C and C++ style comments to appear in whitespace
//opt.allow_trailing_commas = true;                   // allow an additional trailing comma in object and array element lists
//opt.allow_invalid_utf8 = true;                      // skip utf-8 validation of keys and strings

value jv = parse( "[1,2,3,] // comment ", storage_ptr(), opt );

This should do what you want. You'll probably need to read your file as text first, though.

nick
  • 541
  • 1
  • 9
  • I'm not entirely clear on the usage of that storage_ptr (info here: https://www.boost.org/doc/libs/develop/libs/json/doc/html/json/allocators/storage_ptr.html). But you'll figure it out ! ;) – nick Nov 08 '22 at 16:02
  • 1
    You can just default it as you did (or just `{}`) unless you want to control/reuse allocation – sehe Nov 09 '22 at 00:26
  • @nick Hi, thanks for your idea. Unfortunately, I'm using boost 1.62, JSON lib wasn't introduced in that version... So I have to write some c++ code to remove "//" or "/* */" manually before feeding it into read_json. Maybe somebody could validate your mentioned solution. – terry Nov 09 '22 at 14:30
  • @terry: Oooh, right. That's why have that property_tree stuff there. Sorry. Time to update then ! (but you already knew that ;) ) The C++ comment formatting rules are not too complex, fortunatly. – nick Nov 09 '22 at 16:20