解析包含多个文档和访问对象的 YAML [英] Parsing YAML containing multiple documents and accessing objects

查看:31
本文介绍了解析包含多个文档和访问对象的 YAML的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从我的 Perl 脚本的 YAML 文件中获取数据.

以下是类似的示例场景:

让我们考虑一个用于员工数据的 YAML 文件.

---emp_name: 约翰员工年龄:27出生日期:1/1/1990其他:- 键 1:值 1- 键 2:值 2---emp_name:母鹿员工年龄:25出生日期:1/1/1992其他:- 键 1:值 1- 键 2:值 2---emp_name: foo员工年龄:22出生日期:1/1/1995其他:- 键 1:值 1- 键 2:值 2---emp_name: 酒吧员工年龄:21出生日期:1/1/1996其他:- 键 1:值 1- 键 2:值 2...

我有以上四组值.我正在尝试将所有员工姓名保存在一个数组中,但无法获取.

使用 Dumper 我只能将第一部分(John 的)文件打印为 JSON.我无法获取单个值(例如,获取数组中的所有员工姓名).

使用严格;使用警告;使用 YAML::XS 'LoadFile';使用数据::倾销者;我的 $config = LoadFile('input2.yml');打印 Dumper($config), '\n';打印预期输出:\n";打印John \nDoe \nfoo \nBar\n";打印---实际输出--";我的 $empName;for(my $i=0; $i<4; $i++){$empName = $config->[$i]->{emp_name};}

有什么帮助吗?

以上是代码.我想获取员工姓名列表,但出现错误:

<块引用>

yamlParser.pl 第 15 行不是 ARRAY 引用

解决方案

呈现的 yaml 提供了 4 个文档,而不是包含 4 个项目的数组,因此您只需要取消引用它们.阅读文档:perldoc YAML::XS>

变化:

my $config = LoadFile('input2.yml');

致:

my @conf = LoadFile('input2.yml');我的 $config = \@conf;

I am trying to get data from a YAML file for my Perl script.

Following is a similar sample scenario:

Let us consider a YAML file for employee data.

---
emp_name: John
emp_age: 27
DOB: 1/1/1990
others:
  - key1: value1
  - key2: value2
---
emp_name: Doe
emp_age: 25
DOB: 1/1/1992
others:
  - key1: value1
  - key2: value2
---
emp_name: foo
emp_age: 22
DOB: 1/1/1995
others:
  - key1: value1
  - key2: value2
---
emp_name: Bar
emp_age: 21
DOB: 1/1/1996
others:
  - key1: value1
  - key2: value2
...

I have the above four set of values. I'm trying to get all employee names saved in an array, but I'm unable to get it.

With Dumper I am able to print only the first section (John's) file as a JSON. I'm not able to get individual values (eg. get all employee name in an array).

use strict;
use warnings;
use YAML::XS 'LoadFile';
use Data::Dumper;
my $config = LoadFile('input2.yml');
print Dumper($config), '\n';
print "Expected output:\n";
print "John \nDoe \nfoo \nBar\n";
print "--- Actual Output --";
my $empName;
for(my $i=0; $i<4; $i++)
{
$empName = $config->[$i]->{emp_name};
}

Any help?

The above is the code. I would like to fetch list of employee names, but I get an error:

Not an ARRAY reference at yamlParser.pl line 15

解决方案

The yaml presented offers 4 documents, not an array of 4 items, so you just need to dereference those. Have a read of the docs: perldoc YAML::XS

Change:

my $config = LoadFile('input2.yml');

To:

my @conf = LoadFile('input2.yml');
my $config = \@conf;

这篇关于解析包含多个文档和访问对象的 YAML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆