将JSON数据放入yml文件

时间:2020-09-24 08:55:43

标签: json ruby yaml

我有一个ruby文件,该文件返回JSON数据结构

    class BankDetails
      DETAILS = [
    {
      currencyCode: 'usd',
      currencyName: 'United States Dollar',
      iban: 'CH13 0070 0130 0089 9043 3',
      bankName: 'Zürcher Kantonalbank',
      bic: 'ZKBKCHZZ80A',
    },
    {
      currencyCode: 'chf',
      currencyName: 'Swiss Franc',
      iban: 'CH60 0070 0110 0067 2153 4',
      bankName: 'Zürcher Kantonalbank',
      bic: 'ZKBKCHZZ80A',
    },
    {
      currencyCode: 'eur',
      currencyName: 'Euro',
      iban: 'CH88 0070 0130 0089 9044 1',
      bankName: 'Zürcher Kantonalbank',
      bic: 'ZKBKCHZZ80A',
    },
    {
      currencyCode: 'zar',
      currencyName: 'South African Rand',
      iban: 'CH60 0070 0110 0067 2153 4',
      bankName: 'Zürcher Kantonalbank',
      bic: 'ZKBKCHZZ80A',
    },
    {
      currencyCode: 'nad',
      currencyName: 'Namibian Dollar',
      iban: 'CH60 0070 0110 0067 2153 4',
      bankName: 'Zürcher Kantonalbank',
      bic: 'ZKBKCHZZ80A',
    },

  ].freeze

  def self.fetch_bank_details
    DETAILS
  end
end

现在,我想将相同的JSON放入新的yml文件中,并以与通过从ruby文件中调用BankDetails类获得的结构相同的方式获取数据。 yml文件的确切结构应该是什么?

1 个答案:

答案 0 :(得分:1)

从技术上来说,您所显示的既不是YAML也不是JSON,而是一个包含哈希的Ruby数组。

在此语法中,它不是有效的JSON。通过修复语法问题(引用键,删除结尾的逗号),您可以获得几乎等效的JSON表示(只要您指示解析器将Hash键作为符号而不是字符串读取即可)。

如果您选择了正确的代码子集,则它可能是有效的YAML,尽管以这种方式进行解析不会获得与该YAML完全相同的数据结构,但哈希键将再次解析为String而不是Symbols

因此,要获得数据结构的等效YAML表示形式,您只需使用YAML.dump从现有数据结构中发出YAML文档:

require 'yaml'
puts YAML.dump(BankDetails::Details)