将 Ruby 数组解析为 JSON

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18127066/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 19:41:51  来源:igfitidea点击:

Parsing a Ruby Array to JSON

rubyjson

提问by pablo808

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?

我需要将其转换为 json。如果结果是标准的 csv 格式,那么它会很简单,但是如果结果格式看起来像上面那样,如何处理呢?

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

采纳答案by Abe Voelker

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

回答by bmalets

Look at to_jsonmethod.

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

回答by T145

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

您将“标题”分配到 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

Hope it helps!

希望能帮助到你!