11

我有一些结果:

puts result

看起来像这样的输出:

Allowed
20863963
1554906
Denied
3607325
0
Quarantined
156240 
0

调试

p results

输出

[["Allowed", 20863963, 1554906], ["Denied", 3607325, 0], ["Quarantined", 156194, 0]]

标题是:

status,hits,page_views 

我需要将其转换为 json。如果结果是标准 csv 格式,那么这将是直截了当的,但如果结果格式看起来像上面那样,如何处理呢?

预期输出与此类似:

[{"status":"Allowed","hits":"20863963","page_views":"1554906"},{"status":"Denied","hits":"3607325","page_views":"0"},{"status":"Quarantined","hits":"156240","page_views":"0"}]

解决方案

a = result.map{|s| {status: s[0], hits: s[1].to_i, page_views: s[2].to_i} }
puts a.to_json
4

3 回答 3

17

to_json方法。

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}" 
于 2013-08-08T14:43:53.587 回答
6
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}]"
于 2013-08-08T13:22:36.657 回答
2

您将“标题”分配给 attr_accessor,然后告诉 JSON 解析该符号。这是一个例子:

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

希望能帮助到你!

于 2013-08-08T13:32:17.203 回答