1 格式化json字符串

1.1 目的

C++ nlohmann json得到的字符串都是一整块的输出结果,对于json字符串的层次结构展示的不是很清晰,希望在打印json字符串的时候可以在控制台中看到层次结构分明的json字符串。

例如将:

{"Peoples":[{"name":"张三","age":18,"sex":"man"},{"name":"张美","age":18,"sex":"woman"}]}

转化为:

{
    "Peoples": [
        {
            "name": "张三",
            "age": 18,
            "sex": "man"
        }, 
        {
            "name": "张美",
            "age": 18,
            "sex": "woman"
        }
    ]
}

1.2 json字符串格式化代码

#include <iostream>
#include <sstream>
#include <iomanip>


std::string getLevelStr(int level)
{
    std::string levelStr = "";
    for (int i = 0; i < level; i++)
    {
        levelStr += "    ";
    }
    return levelStr;

}

std::string FormatJsonToDisplay(std::string json)
{
    std::string result = "";
    int level = 0;
    for (std::string::size_type index = 0; index < json.size(); index++)
    {
        char c = json[index];

        if (level > 0 && '\n' == json[json.size() - 1])
        {
            result += getLevelStr(level);
        }

        switch (c)
        {
        case '{':
        case '[':
            result = result + c + "\n";
            level++;
            result += getLevelStr(level);
            break;
        case ',':
            result = result + c + "\n";
            result += getLevelStr(level);
            break;
        case '}':
        case ']':
            result += "\n";
            level--;
            result += getLevelStr(level);
            result += c;
            break;
        default:
            result += c;
            break;
        }

    }
    return result;
}

int main()
{
    std::string inputStr = R"({"Peoples":[{"name":"张三","age":18,"sex":"man"},{"name":"张美","age":18,"sex":"woman"}]})";

    std::cout << "Json格式化前:" << std::endl;
    std::cout << inputStr << std::endl;

    std::string inputStr_format = FormatJsonToDisplay(inputStr);

    std::cout << "Json格式化后:" << std::endl;
    std::cout << inputStr_format << std::endl;

    return 0;
}

运行结果:

C++ – 格式化json字符串,方便展示json字符串的层次结构-StubbornHuang Blog