ZBLOG

json 数据里面包含yaml数据 为: id: 1.2.31 text: 'Ensure that the --etcd-cafile argument is set as appropriate (Automated)' audit: '/bin/ps -ef | grep ${apiserverbin} | grep -v grep' tests: test_items: - ...

使用 nlohmann JSON 库,可以通过以下代码解析包含 YAML 数据的 JSON 数据:

#include <iostream>
#include <nlohmann/json.hpp>

using json = nlohmann::json;

int main() {
    std::string jsonData = R"(
        {
            "id": "1.2.31",
            "text": "Ensure that the --etcd-cafile argument is set as appropriate (Automated)",
            "audit": "/bin/ps -ef | grep ${apiserverbin} | grep -v grep",
            "tests": {
                "test_items": [
                    {
                        "flag": "--etcd-cafile"
                    }
                ]
            },
            "remediation": "| Follow the Kubernetes documentation and set up the TLS connection between the apiserver and etcd.\nThen, edit the API server pod specification file ${apiserverconf}\non the master node and set the etcd certificate authority file parameter.\n--etcd-cafile=<path/to/ca-file>",
            "scored": true
        }
    )";

    try {
        json data = json::parse(jsonData);

        std::cout << "ID: " << data["id"] << std::endl;
        std::cout << "Text: " << data["text"] << std::endl;
        std::cout << "Audit: " << data["audit"] << std::endl;

        // Accessing YAML-like data
        for (const auto& item : data["tests"]["test_items"]) {
            std::cout << "- Flag: " << item["flag"] << std::endl;
        }

        // Printing multiline remediation text
        std::cout << "\nRemediation:\n" << data["remediation"].get<std::string>() << std::endl;

        // Checking scored flag
        std::cout << "Scored: " << (data["scored"].get<bool>() ? "true" : "false") << std::endl;
    }
    catch (json::parse_error& e) {
        std::cerr << "JSON parsing error: " << e.what() << std::endl;
    }

    return 0;
}

这个例子中,我们使用 nlohmann JSON 库解析包含 YAML 数据的 JSON 字符串,并从中提取所需的字段。然后,我们使用标准输出打印出这些字段的值。

请注意,为了方便演示,我们在代码中直接将 JSON 字符串写为一个原始字符串。实际应用中,您可以从文件、网络或其他数据源动态获取 JSON 数据进行解析。


内容由零声教学AI助手提供,问题来源于学员提问

本站部分文章来源于网络,版权归原作者所有,如有侵权请联系站长删除。
转载请注明出处:http://sdn.0voice.com/?id=2077

分享:
扫描分享到社交APP
上一篇
下一篇
发表列表
游客 游客
此处应有掌声~
评论列表

还没有评论,快来说点什么吧~

联系我们

在线咨询: 点击这里给我发消息

微信号:3007537140

上班时间: 10:30-22:30

关注我们
x

注册

已经有帐号?