使用 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助手提供,问题来源于学员提问


 
                             
         
        
 
         
         
         
         
         
         
        
 
                 
                 
                 
                 
                 
                 
                 
                 
                