开发者

ruby yaml ypath like xpath?

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 descr开发者_如何学运维iption 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


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.


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜