0

I have a string std::string sub("{\"color\": \"green\",\"type\": \"primary\"}");. I parse it and the result is:

color:green
type:primary

I want to reorganize the structure to be a valid JSON expression, something like this:

{
"color": "yellow",
"type": "primary"
}

I know that i have to use something like to string method but i don't know how to do this. After this i want to could acces the elemets of the strings, like get(color). NOTE: my color:green, type:primary are std::map<std::string,string> keyVal type.

Nick is tired
  • 6,860
  • 20
  • 39
  • 51
John Smith
  • 45
  • 6

1 Answers1

1

You can use a boost json parser

https://www.boost.org/doc/libs/1_65_1/doc/html/property_tree.html

#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>
#include <iostream>

using namespace boost::property_tree;

int main()
{
    try{
        ptree pt;
        json_parser::read_json("file.json", pt); // <- invalid will be caught
        std::string color = pt.get<std::string>("color");
        std::string something = pt.get<std::string>("root.path.to.key");
    }catch(...)
    {
        std::cout<<"invalid!"<<std::endl;
    }
    return 0;
}

For config style data go for write_info and read_info.

If you prefer to work with strings than files, for string to json properties, follow

const std::string json="{\"color\": \"green\",\"type\": \"primary\"}";
ptree pt;
std::istringstream i_str(json);
read_json(i_str, pt);

and for json properties to a string:

const ptree pt=...;
std::ostringstream buf; 
write_json(buf, pt, false);
std::string json = buf.str(); // {"foo":"bar"}
Arash
  • 2,114
  • 11
  • 16
  • you need to elaborate on that. "boost::write_info" via "std::wostringstream", etc. – Red.Wave Jul 16 '18 at 09:30
  • it is on hold(why?).but: wostringstream str; write_json(str,pt); cout< – Red.Wave Jul 16 '18 at 11:44
  • @Red.Wave, the question is a bit vague to me. But thank you very much for mentioning this. – Arash Jul 16 '18 at 15:30
  • y r welcome. that could be my answer in your absence. I guess the OP needs the output in a string, rather than a file. Therefore the more generic answer would be the one involving iostreams instead of filenames. – Red.Wave Jul 16 '18 at 15:51