ruby yaml ypath 和 xpath 一样吗?

发布于 2024-08-26 10:12:16 字数 402 浏览 7 评论 0原文

您好,我有一个像这样的 yaml 文件,

---
data:
  - date: "2004-06-11"
    description: First description

  - date: "2008-01-12"
    description: Another descripion

我如何执行类似于 xml 的 xpath 的“ypath”查询?类似“获取日期为 2004-06-11 的描述”之类的内容,

YAML.parse_file('myfile.yml').select('/data/*/date == 2004-06-11')

你是如何做到的,如果可能的话,我如何通过 'ypath' 类似地编辑描述?

谢谢

Hi i have a yaml file like so

---
data:
  - date: "2004-06-11"
    description: First description

  - date: "2008-01-12"
    description: Another descripion

How can i do a "ypath" query similar to xpath for xml ? Something like "get the description where the date is 2004-06-11"

YAML.parse_file('myfile.yml').select('/data/*/date == 2004-06-11')

How do you do it, and if that's possible how can i similarly edit the description by 'ypath' ?

Thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

情域 2024-09-02 10:12:16

确实像YPath这样的东西:github.com/peterkmurphy/YPath-Specification< /a>

它是在 Ruby 的 YAML 库中实现的;请参阅 BaseNode#search 的文档。

There is indeed such thing as YPath: github.com/peterkmurphy/YPath-Specification

And it's implemented in Ruby's YAML lib; see the doc for BaseNode#search.

不奢求什么 2024-09-02 10:12:16

If Ruby is not a hard constraint you might take a look at the dpath tool.
It provides an xpath-like query language to YAML (and other) files. Maybe call
it externally to filter your data.

那支青花 2024-09-02 10:12:16

yaml 文件描述了从字符串到哈希数组(从字符串映射到字符串)的哈希映射。没有用于嵌套哈希的 xpath 之类的东西(至少在标准库中没有),但是使用标准 Hash 和 Enumerable 方法就足够简单了:

hash = YAML.load_file('myfile.yml')
item = hash["data"].find {|inner_hash| inner_hash["date"] == "2004-06-11"}
#=> {"date"=>"2004-06-11", "description"=>"First description"}

要更改描述,您可以简单地执行 item["description"] =“新描述”,然后使用 hash.to_yaml 将哈希序列化回 YAML。

The yaml file describes a hash mapping from strings to arrays of hashes that map from strings to strings. There is no such thing as xpath for nested hashes (at least not in the standard library), but it's simple enough with standard Hash and Enumerable methods:

hash = YAML.load_file('myfile.yml')
item = hash["data"].find {|inner_hash| inner_hash["date"] == "2004-06-11"}
#=> {"date"=>"2004-06-11", "description"=>"First description"}

To change the description, you can then simply do item["description"] = "new description" and then serialize the hash back to YAML using hash.to_yaml.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文