hhanzo1
hhanzo1

Reputation: 657

Parsing a Ruby Array to JSON

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

Upvotes: 12

Views: 44789

Answers (3)

bmalets
bmalets

Reputation: 3297

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}" 

Upvotes: 18

T145
T145

Reputation: 69

You assign your "headers" into the attr_accessor and then tell JSON to parse that symbol. Here's an example:

class Document
  attr_accessor :content

  def content
    metadata[:content] || metadata['content']
  end

  def self.parse_contents
    txt = File.read(path, {mode: 'r:bom|utf-8'})

    page = Document.new
    page.metadata = JSON.parse(txt)
    page.content = page.metadata['content']

    return page
  end
end

Hope it helps!

Upvotes: 2

Abe Voelker
Abe Voelker

Reputation: 31622

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}]"

Upvotes: 7

Related Questions