ruby将json数据打印成表格格式

时间:2018-02-04 03:15:18

标签: ruby hash

我有一些文件有散列格式的数据,我试图以表格格式打印,

{
  :outerkey1 => "value1", 
  :innerhash => { 
    :doubleinnerhash => { 
      :key1 => "", 
      :key2 => true, 
      :key3 => 0, 
      :key4 => "line1\nline2\n line3\nline4\n"
     },
     :innerkey => "OK",
     :innerkey3 => 0
   }, 
   :outerkey2 => "value2", 
   :outerkye3 => "value3", 
   :outerkey4 => "value4"
}

在上面的格式化数据中,想要解析outerkeydoubleinnerhash的哈希值,然后以tabluar格式打印以显示它。

我在Python - Printing a dictionary as a horizontal table with headers的帮助下对Python有所了解但是如果想要实现那么我需要将这个Ruby哈希转换为Python Dict格式,这将导致数据不一致问题。

我希望低于格式化输出,

|----------------------------------------------------|
|outerkey1 | key1   |   key2    |   key3    |   key4 |
|----------------------------------------------------|
|value1    |        |   true    |   0       |   line1|
|          |        |           |           |   line2|
|          |        |           |           |   line3|
|          |        |           |           |   line4|
|----------------------------------------------------|
|value2    |error   |   false   |   2       |   line1|
|          |        |           |           |   line2|
|          |        |           |           |   line3|
|          |        |           |           |   line4|
|----------------------------------------------------|

那么有没有直接的机制让这个工作在Ruby?

2 个答案:

答案 0 :(得分:0)

我不知道会自动执行嵌套数据处理的任何内容,但此库可以帮助输出的固定字符宽度格式:https://github.com/piotrmurach/tty-table

那就是说,我建议尽可能多地使用JSON或YAML - 是否有理由包含数据的文件不使用其中一种格式?或者是他们?

答案 1 :(得分:0)

有几种宝石可用,但在大多数花瓶中,您需要修改输入。

宝石text-tabl似乎对我来说是一个很好的候选人。

这是一个例子

require 'text-table'

table = Text::Table.new
table.head = ['A', 'B']
table.rows = [['a1', 'b1']]
table.rows << ['a2', 'b2']

table.to_s

#    +----+----+
#    | A  | B  |
#    +----+----+
#    | a1 | b1 |
#    | a2 | b2 |
#    +----+----+

所以你必须将你的哈希值转换为这个gem的数组数组。

我不会完全解决这个问题(哪个会对你有意思?)但这里有一篇文章可以帮助你开始......

h = {
  :outerkey1 => "value1", 
  :innerhash => { 
    :doubleinnerhash => { 
      :key1 => "", 
      :key2 => true, 
      :key3 => 0, 
      :key4 => "line1\nline2\n line3\nline4\n"
     },
     :innerkey => "OK",
     :innerkey3 => 0
   }, 
   :outerkey2 => "value2", 
   :outerkye3 => "value3", 
   :outerkey4 => "value4"
}

header = [h.keys.first, h[:innerhash][:doubleinnerhash].keys].flatten
rows   = h[:innerhash][:doubleinnerhash].values
相关问题