Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing a Ruby Array to JSON

Tags:

json

ruby

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
like image 924
pablo808 Avatar asked Aug 08 '13 13:08

pablo808


People also ask

Is JSON parse safe Ruby?

JSON isn't code, you can't inject harmful values into it. JSON. parse is safe.

How does Ruby process JSON data?

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.

What does JSON parse return in Ruby?

body), it returns an Array.


2 Answers

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}]"
like image 121
Abe Voelker Avatar answered Oct 24 '22 01:10

Abe Voelker


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}" 
like image 26
bmalets Avatar answered Oct 24 '22 01:10

bmalets