合并JSON成YAML与缩进

问题描述 投票:1回答:2

我试图将一个JSON到一个YAML文件。 该YAML看起来是这样的: filebeat.inputs:

- type: log  
  <incorporate here with a single level indent>
  enabled: true  
  paths:  

假设你有以下变量:

a = { processors: { drop_event: { when: { or: [ {equals: { status: 500 }},{equals: { status: -1 }}]}}}}  

我想要将它整合到现有的YAML。 我试着使用:

JSON.parse((a).to_json).to_yaml

应用此之后,我得到了一个有效的YAML但无压痕(所有行必须缩进),并用“---”这是YAML Ruby的新文档。 结果:

filebeat.inputs:
- type: log
---
processors:
  drop_event:
    when:
      or:
      - equals:
          status: 500
      - equals:
          status: -1
  enabled: true

我在寻找的结果是:

filebeat.inputs:
- type: log
  processors:
    drop_event:
      when:
        or:
        - equals:
            status: 500
        - equals:
            status: -1
  enabled: true```
json ruby yaml chef
2个回答
2
投票

它更容易通过合并哈希产生一个有效的红宝石对象,然后序列化的结果比反之亦然YAML。

puts(yaml.map do |hash|
  hash.each_with_object({}) do |(k, v), acc|
    # the trick: we insert before "enabled" key
    acc.merge!(JSON.parse(a.to_json)) if k == "enabled"
    # regular assignment for all hash elements
    acc[k] = v
  end
end.to_yaml)

结果是:

---
- type: log
  processors:
    drop_event:
      when:
        or:
        - equals:
            status: 500
        - equals:
            status: -1
  enabled: true

JSON.parse(a.to_json)基本符号转换为字符串。


-1
投票

为了做到这一点,首先您需要到原来的YAML转换成JSON

original = YAML.load(File.read(File.join('...', 'filebeat.inputs')))
# => [
       {
         "type": "log", 
         "enabled": true, 
         "paths": null
       }
     ]

然后你要合并的JSON这个original变量

original[0].merge!(a.stringify_keys)
original.to_yaml
# => 
---
-
  type: log
  enabled: true
  paths:
  processors:
    drop_event:
      when:
        or:
        - equals:
            status: 500
        - equals:
            status: -1
© www.soinside.com 2019 - 2024. All rights reserved.