Parsing a Ruby Array to JSON -
i have results:
puts result that output:
allowed 20863963 1554906 denied 3607325 0 quarantined 156240 0 debug
p results output
[["allowed", 20863963, 1554906], ["denied", 3607325, 0], ["quarantined", 156194, 0]] the headers are:
status,hits,page_views i need convert json. if results in standard csv format straight forward how 1 approach if results format looked above?
expected output similar this:
[{"status":"allowed","hits":"20863963","page_views":"1554906"},{"status":"denied","hits":"3607325","page_views":"0"},{"status":"quarantined","hits":"156240","page_views":"0"}] solution
a = result.map{|s| {status: s[0], hits: s[1].to_i, page_views: s[2].to_i} } puts a.to_json
output = "allowed 20863963 1554906 denied 3607325 0 quarantined 156240 0" = output.split("\n").each_slice(3).map{|s| {status: s[0], hits: s[1].to_i, page_views: s[2].to_i} } # => [{:status=>"allowed", :hits=>20863963, :page_views=>1554906}, {:status=>"denied", :hits=>3607325, :page_views=>0}, {:status=>"quarantined", :hits=>156240, :page_views=>0}] a.to_json # => => "[{\"status\":\"allowed\",\"hits\":20863963,\"page_views\":1554906},{\"status\":\"denied\",\"hits\":3607325,\"page_views\":0},{\"status\":\"quarantined\",\"hits\":156240,\"page_views\":0}]"
Comments
Post a Comment