如何从符合条件的JSON中提取数据?

时间:2014-09-06 05:23:34

标签: ruby json

我有一个JSON file,我想只获取符合条件的所有值的键。即(屏幕> 7%)和(jira> 8)。以下是JSON文件。

    {
  "screen": {
      "/theaters":            16.86,
      "/boxoffice":           12.87,
      "/theater/info":        11.07,
      "/theater/tickets":     7.00,
      "/TopBoxOffice":        4.34,
      "/upcoming":            4.02,
      "/new-releases":        3.49,
      "/trailer":             3.49,
      "/showtimes":           3.39,
      "/DvdOther":            3.13,
      "/MOB":                 2.85
  },

  "jira": {
      "theater":                      12,
      "showtime":                     11,
      "quantity":                     3,
      "card":                         4,
      "review":                       1,
      "confirm":                      1
    }

}

输出应该是这样的:

screen = ["/theaters", "/boxoffice", "/theater/info"]
jira = ["theater", "showtime" ]

我目前的实现如下:

file      = File.read('ga_jira.json')
data_hash = JSON.parse(file)
screen    = data_hash['screen']
jira      = data_hash['jira']

pp screen.select {|k,v| k > 7}
pp jira.select {|k,v| k > 7}

提前感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

我认为您的使用没有任何问题。你得到了什么?

require 'json'

s = '{
 "screen": {
     "/theaters":            16.86,
  ...'

JSON.parse(s)['screen'].select{|k,v| v > 7 }
=> {"/theaters"=>16.86, "/boxoffice"=>12.87, "/theater/info"=>11.07}

JSON.parse(s)['jira'].select{|k,v| v > 7 }
=> {"theater"=>12, "showtime"=>11}

JSON.parse(s)['screen'].select{|k,v| v > 7 }.keys
=> ["/theaters", "/boxoffice", "/theater/info"]

JSON.parse(s)['jira'].select{|k,v| v > 7 }.keys
=> ["theater", "showtime"]