将JSON数据嵌入到YAML文件中

我正在为我的桌子写一个夹具。 并且其中一个coloums将JSON字符串作为值。

问题是夹具没有加载失败,因为:

Fixture::FormatError: a YAML error occurred parsing /home/saurajeet/code/dcbox/test/fixtures/hardware.yml. Please note that YAML must be consistently indented using spaces. Tabs are not allowed. Please have a look at http://www.yaml.org/faq.html The exact error was: ArgumentError: syntax error on line 145, col 73: ` portslist: [{"name":"ob1","port_num":0,"port_type":"network"},{"name":"ob2","port_nu'..... 

任何解决方案。

我相信把它变成引号应该可以解决问题:

 portslist: '[{"name":"ob1","port_type" ... }]' 

clarkevans对接受的答案的评论为长篇JSON提供了更好的答案,因为你可以包装这些行。 我查看了他提到的块标量语法,并认为我会在这里包含一个示例:

 portslist: > [{"name":"ob1","port_num":0,"port_type":"network"}, {"name":"ob2","port_nu... 

如果你有字符串,你可以像Vlad Khomich提到的那样简单:

 portslist: '[{"name":"ob1","port_num":0,"port_type":"network"},...]' 

如果您正在使用ERB并拥有一个对象,则可以使用to_json并检查以转义为JSON字符串:

 portslist: <%= [{name: 'ob1', port_num: 0, port_type: 'network'},...].to_json.inspect %> 

如果你有一个大的JSON规范,你可以将它存储在一个单独的文件中并使用Ruby加载,这样你就可以保持你的YAML文件干净:

 portslist: <%= File.read('/path/to/file.json').inspect %> 

为了完整起见:如果您正在使用ActiveRecord::Store ,您可以使用相同数据的YAML表示来加载数据,即使它是JSON存储:

 one: portslist: - name: 'ob1' port_num: 0 port_type: 'network' - name: 'ob2' port_num: 1 port_type: 'network' 

在我的表中,列stripe_connect的类型为JSONB 。 在夹具中,这是有效的。 请注意,外部单引号是必需的,但方括号不是。 单引号之间的所有内容都是一条长线。

  stripe_connect: '{"scope":"read_write", "livemode":false, "token_type":"bearer", "access_token":"sk_test_madeupvalue", "refresh_token":"rt_Ae29madeupvalueyX", "stripe_user_id":"acct_103yZabcdefg", "stripe_publishable_key":"pk_test_0HEOmadeupvalue"}'