I have some results:
puts result
That look like this 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 to convert this to json. If the results was in standard csv format then it would be straight forward but how would one approach it if the results format looked like above?
Expected output something similar to 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
JSON isn't code, you can't inject harmful values into it. JSON. parse is safe.
Once we have the file loaded, we can parse the JSON data using the JSON. parse method. This method will create a Ruby hash with the JSON keys. Once loaded, we can proceed to work with the data like an ordinary Ruby hash.
body), it returns an Array.
output = "Allowed
20863963
1554906
Denied
3607325
0
Quarantined
156240
0"
a = 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}]"
Look at to_json
method.
require 'json'
# => true
h = {a: 1, b: 2,c: 3}
# => {a: 1, b: 2,c: 3}
h.to_json
# => "{\"a\":1,\"b\":2,\"c\":3}"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With