简体   繁体   中英

Converting array to json in Ruby (Puppet, facter)

I'm writing a fact for Puppet in Ruby. I have an array

array = [[["User", "Username"], ["Date", "16.12.2014"]], [["User1", "Username1"], ["Date1", "17.12.2014"]]]

I want to convert it to json. I tried to convert it to hash first, but doing like this in Linux

array.each do |userarr|
  winusers = Hash[userarr.map! { |pair| [pair[0], pair[1]] } ]
end

I get only the this one [["User1", "Username1"], ["Date1", "17.12.2014"]] pair converted. Doing like this:

array.each do |userarr|
  winusers = Hash[userarr.map! { |pair| [pair[0], pair[1]] } ]
  winusersa << winusers
end

I get an array of hashes. Coverting it to json winusersa.to_json on Linux I get an array of json format text, on Puppet (facter in fact) I get only the first pair converted. Why in Puppet fact it doesn't work? How to convert that array to get all pairs well formated?

Try this one

array.flatten(1).each_slice(2).map(&:to_h)
 => [{"User"=>"Username", "Date"=>"16.12.2014"}, {"User1"=>"Username1", "Date1"=>"17.12.2014"}] 

And then, as an hash, you can easily call to_json

Require 'facter' #if you have facter as gem to test locally require 'json'

array = [
    [
        ["User", "Username"],
        ["Date", "16.12.2014"]
    ],
    [
        ["User1", "Username1"],
        ["Date1", "17.12.2014"]
    ]
]

put JSON.pretty_generate(JSON.parse(array.to_json))

You've already got your Array in the form that the ruby Hash#[] method can consume. I think all you need is this:

% pry
[1] pry(main)> require 'json'
[2] pry(main)> a = [[["User", "Username"], ["Date", "16.12.2014"]], [["User1", "Username1"], ["Date1", "17.12.2014"]]]
[3] pry(main)> puts JSON.pretty_generate(a.map { |e| Hash[e] })
[
  {
    "User": "Username",
    "Date": "16.12.2014"
  },
  {
    "User1": "Username1",
    "Date1": "17.12.2014"
  }
]

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