12

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
3
  • 2
    What kind of object result is? An array? Can you please post the output you expect to get? Commented Aug 8, 2013 at 13:21
  • added to original post. thx Commented Aug 8, 2013 at 13:31
  • 1
    What code did you write to solve this? It's a really easy thing to do. Commented Aug 8, 2013 at 15:04

3 Answers 3

18

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}" 
Sign up to request clarification or add additional context in comments.

Comments

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

1 Comment

I had to update the output, and resolved it by looking at your answer.
2

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!

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.