Sunrise487
Sunrise487

Reputation: 11

Parse Nested YAML into Key Value Pairs with Ruby

I am looking to solve parsing YAML data like this with ruby

access_log:
  stored_proc: getsomething
    uses:
      usedin: some breadcrumb

I was able to parse into key-pair for (access_log>> stored_proc>> getsomething ) but having issues with flow for(access_log >> uses >> usedin >> some breadcrumb) to have usedin >> some breadcrumb as key value pair. I would appreciate your help

Upvotes: 0

Views: 1507

Answers (2)

Hirurg103
Hirurg103

Reputation: 4953

Your YAML is malformed. You cannot have key with a value and something else nested under that key

# malformed.yml
access_log:
  stored_proc: getsomething
    uses:
      usedin: some breadcrumb

# irb
YAML.load_file 'malformed.yml'
Psych::SyntaxError: (malformed.yml): mapping values are not allowed in this context at line 3 column 9
    from (irb):51

The correct structure will be

access_log:
  stored_proc: getsomething
  uses:
    usedin: some breadcrumb

Upvotes: 1

Sebastián Palma
Sebastián Palma

Reputation: 33420

Maybe is your YAML structure (?):

# data.yml
- access_log:
  - stored_proc: getsomething
    uses:
      usedin: some breadcrumb

# file.rb
require 'yaml'

data = YAML.load_file '/Users/seb/Desktop/data.yaml'
p data.first['access_log']                         # [{"stored_proc"=>"getsomething", "uses"=>{"usedin"=>"some breadcrumb"}}]
p data.first['access_log'].first['stored_proc']    # "getsomething"
p data.first['access_log'].first['uses']           # {"usedin"=>"some breadcrumb"}
p data.first['access_log'].first['uses']['usedin'] # "some breadcrumb"

Upvotes: 0

Related Questions