【问题标题】:Put JSON data in yml file将 JSON 数据放入 yml 文件中
【发布时间】:2020-09-24 08:55:43
【问题描述】:

我有一个返回 JSON 数据结构的 ruby​​ 文件

    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 文件的具体结构应该是什么?

【问题讨论】:

  • 首先,您可以简单地在 YAML 文件中使用 JSON。 JSON 是 YAML 的子集。
  • 这种结构可以工作吗? default: bank_details: - currency_code: usd currency_name: United States Dollar iban: CH13 0070 0130 0089 9043 3 bank_name: Zürcher Kantonalbank bic: ZKBKCHZZ80A - currency_code: chf currency_name: Swiss Franc iban: CH60 0070 0110 0067 2153 4 bank_name: Zürcher Kantonalbank bic: ZKBKCHZZ80A

标签: json ruby yaml


【解决方案1】:

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

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

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

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

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

【讨论】:

  • 这种结构会起作用吗? default: bank_details: - currency_code: usd currency_name: United States Dollar iban: CH13 0070 0130 0089 9043 3 bank_name: Zürcher Kantonalbank bic: ZKBKCHZZ80A - currency_code: chf currency_name: Swiss Franc iban: CH60 0070 0110 0067 2153 4 bank_name: Zürcher Kantonalbank bic: ZKBKCHZZ80A
  • 从您评论中的格式无法判断。但是,您可以通过使用 YAML.load_file('/path/to/file') 解析文件并将解析的数据结构与原始数据结构进行比较来自行检查。
  • 我应该在哪里写这段代码? YAML.load_file('/path/to/file')
猜你喜欢
  • 1970-01-01
  • 2022-09-23
  • 1970-01-01
  • 2017-03-01
  • 1970-01-01
  • 2019-06-15
  • 2021-12-30
  • 2011-11-18
  • 1970-01-01
相关资源
最近更新 更多