简体   繁体   中英

Convert YAML string to JSON using Ruby

I am able to convert a YAML file to JSON, but I am not able to convert a YAML string to JSON. Is there any other way to convert YAML string to JSON?

Sample Input

---
:name:
  :firstname: Guru
  :lastname: Shyam

Expected output

{
  "name": {
    "firstname": "Guru",
    "lastname": "Shyam"
  }
}

Try Pysch.load

data = "---\n:name:\n  :firstname: Guru\n  :lastname: Shyam\n"

Psych.load(data)
-> {
     :name => {
         :firstname => "Guru", 
         :lastname=> "Shyam"
        }
   }

YAML.load_file might help you.

Btw, it is an alias for Psych but has a more convenient name, and included in ruby standart library.

[2] pry(main)> .cat data.yml
---
:name:
  :firstname: Guru
  :lastname: Shyam
[3] pry(main)> require 'yaml'
=> true
[4] pry(main)> puts YAML.load_file('data.yml').to_json
{"name":{"firstname":"Guru","lastname":"Shyam"}}
=> nil

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM