【问题标题】:Loading and generating Yaml file with similar keys使用相似键加载和生成 Yaml 文件
【发布时间】:2011-09-16 08:00:47
【问题描述】:

我有一个具有相似键的 yaml 文件文档:-

sample_file.yml

line:
  title: line-name
  department: transcription

  input_formats:
    - input_format:
        name: company
        required: true
        valid_type: general
    - input_format:
        name: website
        required: false
        valid_type: url

生成 new_file.yml 后,键按字母顺序排序:-

new_file.yml

line: 
  department: transcription
  input_formats: 
    - 
      input_format: 
      name: company
      required: true
      valid_type: general
    - 
      input_format: 
      name: website
      required: false
      valid_type: url

  title: line-name

打开sample_file和制作new_file的代码如下:-

require 'yaml'
require 'ya2yaml'


@file = YAML::load(File.open("/Users/manish/Desktop/yaml/sample_file.yml"))
@new_file = File.new("/Users/manish/Desktop/yaml/new_file.yml", "w+") 
@new_file.syswrite(@file.ya2yaml(:hash_order => ['title','department','input_formats']))

我正在使用“ya2yaml”gem 来生成 yaml 文件。为了获得与 sample_file.yml 中相同的顺序,我在这里使用了 hash_order @new_file.syswrite(@file.ya2yaml(:hash_order => ['title','department','input_formats'])),但它不起作用。如何保留订单?

【问题讨论】:

  • 您的第一个 yaml 文件不仅有重复的键,而且在最后一个 'station' 节中的格式也无效 - 'worker' 应该与 'station_type' 对齐。

标签: ruby-on-rails ruby ruby-on-rails-3 rubygems yaml


【解决方案1】:

最后我得到了订购问题的解决方案。

:hash_order 仅适用于顶级哈希。
所以它仅在我从我的 sample_file.yml 中删除“line”键时才有效。然后订单被保留。 :-

title: line-name
department: transcription

input_formats:
  - input_format:
      name: company
      required: true
      valid_type: general
  - input_format:
      name: website
      required: false
      valid_type: url

【讨论】:

  • @Andy,感谢 Andy 解决重复密钥问题
【解决方案2】:

你能改变 YAML 文件的格式吗?您的 YAML 文件指定具有重复键的哈希。这是不行的。

如果 YAML 文件改为使用列表,如下所示:

line:
    title: line-name
    department: transcription

    formats:
        - input_format:
          name: company
          required: true
          valid_type: general

        - input_format:
          name: website
          required: false
          valid_type: url
....

那些额外的破折号会为你解决你的问题。

【讨论】:

  • 感谢您为重复键工作的方式,但顺序按字母顺序排序,我已相应地编辑了我的问题。
【解决方案3】:

YAML 旨在存储键值对,因此它们的顺序对 YAML 并不是特别重要。

可能解决您的问题的是使用 Ruby 1.9.2,它尊重哈希中的插入顺序(在 Ruby 1.8.7 中不是这种情况)。

【讨论】:

  • 我使用的是 Ruby 1.9.2 版本。
猜你喜欢
  • 2023-04-05
  • 1970-01-01
  • 2019-05-29
  • 2016-03-07
  • 2019-05-16
  • 1970-01-01
  • 2019-05-24
  • 2018-12-13
  • 2017-06-01
相关资源
最近更新 更多