3

I am coding a JSON wrapper for Boost property tree. Currently the focus is on writing the resulting JSON into a string or a file.

Using boost::property_tree::json_parser::write_json(ss, *pt) the resulting property tree is written in a string.

But this method do not understand what is a true, false, null or a number. Everything is converted to a string.

Reading the Boost documentation this is a limitation of the library. Is there any way to modify this behavior?

mariolpantunes
  • 1,114
  • 2
  • 15
  • 28
  • 1
    [Duplicate](http://stackoverflow.com/questions/2855741/why-boost-property-tree-write-json-saves-everything-as-string-is-it-possible-to), as mentioned in the first answer.... although the first answer would be nice to have at the duplicate location. – moodboom Nov 21 '13 at 13:23

1 Answers1

11

Link In this link is a fix for the problem.

It involves changing boost code, because of that I tried another alternative. My solution involves regular expressions:

std::string JSONObject::toString() const
{
    boost::regex exp("\"(null|true|false|[0-9]+(\\.[0-9]+)?)\"");
    std::stringstream ss;
    boost::property_tree::json_parser::write_json(ss, *pt);
    std::string rv = boost::regex_replace(ss.str(), exp, "$1");

    return rv;
}

Basically I search for the keywords: true, false, null and any type of number. The matches are replaced with the same without quotes.

Community
  • 1
  • 1
mariolpantunes
  • 1,114
  • 2
  • 15
  • 28
  • and you move the limitation so that if i want to have a string with only numbers or true/false/null as string - i can't have it :-) however everything is better than changing boost code i suppose. – Alex Kremer Jul 26 '13 at 16:33
  • 1
    Thanks, that regexp saved me some headache. Though it fails with negative numbers a the moment. I've changed it to work with negative numbers too: `"\"(null|true|false|-?[0-9]+(\\.[0-9]+)?)\""` – user2460318 Mar 27 '17 at 11:38