LoginSignup
10
11

More than 5 years have passed since last update.

JSON(Hash)データの階層をツリーで表示する

Last updated at Posted at 2015-03-31

深い階層を持ったJSON(Hash)のキーを一覧で表示させるコードを書きました(探しても無かったので…)。

def show_json_tree(json)
  case json
  when Array
    puts json[0].tree
  when Hash
    puts json.tree
  end
end

class Hash
  def tree
    a = []
    each do |key, value|
      case value
      when String
        a << "#{key}(#{value.class})"
      when Hash
        a << key
        a.concat value.tree.flatten.map{|s| "  " + s }
      when Array
        a << "#{key}(Array of #{value[0].class})"
        a << value[0].tree.map{|s| "  " + s } if Hash === value[0]
      else
        a << "#{key}(#{value.class})"
      end
    end
    a
  end
end

Example

require 'json'
require 'open-uri'
json = JSON.parse open("https://api.deckbrew.com/mtg/cards?oracle=win+the+game&oracle=lose+the+game", &:read)
show_json_tree json
実行結果
name(String)
id(String)
url(String)
store_url(String)
types(Array of String)
subtypes(Array of String)
colors(Array of String)
cmc(Fixnum)
cost(String)
text(String)
power(String)
toughness(String)
formats
  commander(String)
  legacy(String)
  modern(String)
  vintage(String)
editions(Array of Hash)
  set(String)
  set_id(String)
  rarity(String)
  artist(String)
  multiverse_id(Fixnum)
  flavor(String)
  number(String)
  layout(String)
  price
    low(Fixnum)
    median(Fixnum)
    high(Fixnum)
  url(String)
  image_url(String)
  set_url(String)
  store_url(String)

こんな感じで全体の構造を見ることができます。
(Arrayに対しては先頭の要素だけを見て出力しています。)
JSON形式のWebAPIを触るのに便利ではないでしょうか。

実装があまり綺麗ではないのでアドバイス歓迎です。

10
11
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
10
11