c++jsonboostboost-propertytree

How to add a key with a dot in the name to a json file


I am reading some information and I want to write it in json, but the names of some keys contain dots in the name. I want to get something like this:

{
  "programs":
   {
      "tmp.exe" : "D:\\Directory\\Directory",
      "foo.exe" : "C:\\Directory"
   }
}

This is my code:

ptree pt;
ptree name;

name.put(string_name,string_directory);
pt.add_child("programs",name);

But it turns out the following:

    {
      "programs":
       {
          "tmp":
              {
                "exe" : "D:\\Directory\\Directory"
              },
          "foo": 
              {
                "exe" : "C:\\Directory"
              }
       }
    }

I was thinking about adding it as a child. But this code does not work at all

ptree pt;
ptree name;

name.put("",string_name);
pt.add_child("programs",name);
pt.find(string_name).put_value(string_directory);

Solution

  • Although all JSON linters I've tested accepts your target JSON as valid and boost::property_tree::read_json parses it, actually creating it is a bit cumbersome. This is because boost::property_tree uses . as a path separator by default.

    To overcome this, you can specify the Key with a different ptree::path_type than the default in which you specify another character. I've used \ as a path separator here because that's unlikely going to be a part of the basenames of your files.

    Example:

    #include <boost/property_tree/json_parser.hpp>
    #include <boost/property_tree/ptree.hpp>
    
    #include <iostream>
    
    int main() {
        using namespace boost::property_tree;
    
        try {
            ptree pt;
            ptree name;
    
            name.put(ptree::path_type{"tmp.exe", '\\'}, "D:\\Directory\\Directory");
            name.put(ptree::path_type{"foo.exe", '\\'}, "C:\\Directory");
    
            pt.add_child("programs", name);
            write_json(std::cout, pt);
    
        } catch(const std::exception& ex) {
            std::cout << "exception: " << ex.what() << '\n';
        }
    }
    

    Output:

    {
        "programs": {
            "tmp.exe": "D:\\Directory\\Directory",
            "foo.exe": "C:\\Directory"
        }
    }