Skip to content

Instantly share code, notes, and snippets.

@Jackarain
Last active December 17, 2015 09:48
Show Gist options
  • Save Jackarain/5589590 to your computer and use it in GitHub Desktop.
Save Jackarain/5589590 to your computer and use it in GitHub Desktop.
json格式化
#include <boost/foreach.hpp>
#include <boost/property_tree/json_parser.hpp>
namespace pt = boost::property_tree;
using pt::ptree;
template <class Stream>
void list_json(ptree json, Stream &stream, int level = 0)
{
if (level == 0)
{
level++;
stream << "{\n";
}
int s = json.size();
BOOST_FOREACH(ptree::value_type &v, json)
{
if (v.second.size() == 0)
{
for (int i = 0; i < level; i++)
stream << " ";
stream << "\"" << v.first << "\"" << ":" << "\"" << v.second.get_value<std::string>() << "\"";
if (s != 1)
stream << ",";
stream << std::endl;
}
else
{
if (v.first != "")
{
for (int i = 0; i < level; i++)
stream << " ";
stream << "\"" << v.first << "\"" << ":[" << std::endl;
}
else
{
for (int i = 0; i < level; i++)
stream << " ";
stream << "{" << std::endl;
}
list_json(v.second, stream, level + 1);
if (v.first != "")
{
for (int i = 0; i < level; i++)
stream << " ";
if (s != 1)
stream << "]," << std::endl;
else
stream << "]" << std::endl;
}
else
{
for (int i = 0; i < level; i++)
stream << " ";
if (s != 1)
stream << "}," << std::endl;
else
stream << "}" << std::endl;
}
}
s--;
}
if (level == 1)
{
stream << "}";
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment