Or Arnon
Or Arnon

Reputation: 11

Incorporate JSON into YAML with Indentation

I'm trying to incorporate a JSON into a YAML file.
The YAML looks like this:
filebeat.inputs:

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

Suppose you have the following variable:

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

I want to incorporate it into an existing YAML.
I've tried to use:

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

After applying this, I got a valid YAML but without indentation (all lines have to be indented) and with a "---" which is Ruby's new document in YAML.
The result:

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

The result I'm looking for:

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

Upvotes: 1

Views: 599

Answers (2)

mpospelov
mpospelov

Reputation: 1549

In order to do that first you need to convert your original YAML into JSON

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

Then you have to merge your JSON into this original variable

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

Upvotes: -1

Aleksei Matiushkin
Aleksei Matiushkin

Reputation: 121000

It’s easier to produce a valid ruby object by merging hashes and then serialize the result to YAML than vice versa.

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)

Results in:

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

JSON.parse(a.to_json) basically converts symbols to strings.

Upvotes: 2

Related Questions