【问题标题】:Parsing json/yaml array with yaml-cpp使用 yaml-cpp 解析 json/yaml 数组
【发布时间】:2015-05-14 18:37:43
【问题描述】:

我使用 yaml-cpp 来解析我的配置文件,因为我必须能够解析 yaml 和 json 文件,这是我发现的唯一支持 yaml 1.2 的 cpp 库。解析时,我不要求密钥,因为我不知道当前配置文件用于哪个组件。我也使用 ncurses 来显示配置文件内容。

在解析包含数组的配置文件时,我没有得到这些数组。程序只是跳过它们。

yaml配置文件示例:

SLICE_POSITION: 285
SLICE_HEIGHT: 15
OUTPUT_ADDRESS: "localhost:3335"
VIRTCAM_IDS:
            - 0
            - 1
            - 2

json配置文件示例:

{
"width" : 1366,
"mappings" : {
  "x" : [ "mt_position_x" ],
  "y" : [ "mt_position_y" ]
},
"active_quadrangle" : {
  "bottom_left" : "[1472;4698;0]",
  "bottom_right" : "[5654;4698;0]",
  "top_left" : "[1472;1408;0]",
  "top_right" : "[5654;1408;0]"
},
"x" : 0.0,
"y" : 0.0
}

我的代码:

YAML::Node config = YAML::LoadFile(fileName);
for(YAML::const_iterator it = config.begin(); it != config.end();) {
    const char* key = (it->first.as<std::string>()).c_str();
    mvprintw(i, 4, key);
    i++; // row number
    ++it;
}

我从 yaml 文件中获取的密钥:

VIRTCAM_IDS                                   
SLICE_POSITION                                
SLICE_HEIGHT                                  
OUTPUT_ADDRESS   

我从 json 文件中获取的密钥:

uuid                                          
mappings                                      
width                                         
device                                        
sensor_type                                   
target                                        
height                                        
x                                             
active_quadrangle                             
y   

那么有人可以告诉我,如何解析这个,以便我可以访问数组(及其值)吗?还有什么方法可以让我按正确的顺序获取物品?

感谢您的任何回答!

【问题讨论】:

    标签: c++ arrays json yaml yaml-cpp


    【解决方案1】:

    当您在地图中循环时,您只是在读取带有it-&gt;first 的键。要读取这些值,您需要it-&gt;second:

    YAML::Node config = YAML::LoadFile(fileName);
    for (YAML::const_iterator it = config.begin(); it != config.end(); ++it) {
      std::string key = it->first.as<std::string>();
      YAML::Node value = it->second;
      // here, you can check what type the value is (e.g., scalar, sequence, etc.)
      switch (value.Type()) {
        case YAML::NodeType::Scalar: // do stuff
        case YAML::NodeType::Sequence: // do stuff
        // etc.
      }
    }
    

    【讨论】:

    • 哦,谢谢,我试过了,但是我在迭代器上调用了 .Type(),所以它给我抛出了异常。我没有想到要在迭代器值上尝试它。
    猜你喜欢
    • 2015-12-06
    • 2020-10-14
    • 1970-01-01
    • 2018-10-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多