如何从JSON文件中获取数据并使用Ruby中的选定值创建新文件

时间:2017-03-27 11:01:45

标签: json ruby

我需要创建一个JSON文件,其中包含具有相同类型的电影的详细信息。 这是输入JSON文件:

[{"rating": "9.3", "movie_id": 1, "title": "The Shawshank
Redemption",  "release_date": "14 October
1994",  "director": "Frank Darabont", "year":
"1994", "genre": ["Crime", "Drama"], "running_time": "142 min"},

{"rating": "9.2",
"movie_id": 2, "title": "The Godfather",  "director": "Francis Ford",
"year": "1972",
"genre": ["Crime", "Drama"], "running_time": "175 min"},

{"rating": "9.1", "movie_id": 3,  "title": "The Godfather:
Part II",  "release_date": "", "director": "Francis Ford Coppola", "year":
"1974", "genre": ["Crime", "Drama"], "running_time": "200 min"},

{"rating": "9.0",  "movie_id": 12,  "title": "Interstellar",
"release_date": "7 November 2014",
"director": "Christopher Nolan", "year": "2014", 
"genre": ["Adventure",      "Sci-Fi"],
 "running_time": "169 min"},]

如何检查所有电影的类型,并使用" crime"创建一个包含所有电影的新JSON文件。和"戏剧"流派?

3 个答案:

答案 0 :(得分:0)

这是一个简单的方法,我们读取json文件,根据需求将信息取出到ruby散列中,将散列转换为json字符串并将字符串放在json文件中。

require "json"

my_file = JSON.parse(my_file.json) 

#reading the json file
to_be_generated = {}

#This hash will contain our desired  result. Now, let's go for the iteration. Here we check the genre of all the movies listed in the json file. 
#If the genre is ["Crime",  "Drama"], then the title and  (whatever you want to store in the json element) can be stored in a hash. 

for i in 0...my_file.count
      if my_file[i]["genre"] == ["Crime", "Drama"]

          # if you want only to check for Drama, then you can use as [@Neel][1] has pointed out, if my_file[["genre"].include?"Crime"

           to_be_generated.merge!(movie: my_file[i]["title"]) 
      end 

 #Add what else you want here. This is the Ruby hash.
end

json_string = to_be_generated.to_json() 


#It converts the Ruby hash into a json string . Now, the following helps the json string to be stored in a json file. 


File.open("my_json_file.json","w") do |f|
    f.write(json_string)
end

答案 1 :(得分:0)

另一种方法是使用Array#select

selected_movies = json.compact.select { |movie| (["Crime", "Drama"] - movie[:genre]).empty? }

# or

selected_movies = json.compact.select { |movie| movie[:genre] == "Crime" && movie[:genre] == "Drama" }

File.open('selected_movies.json', 'w') { |f| f.puts selected_movies.to_json }

答案 2 :(得分:0)

使用select

时,这是一个简单的问题
require 'json'

json_data = '
[{"rating":"9.3", "title":"The Shawshank Redemption", "genre":["Crime", "Drama"]},
{"rating":"9.0", "title":"Interstellar", "genre":["Adventure", "Sci-Fi"]}]'

output_json = JSON[json_data].select { |hash|
  hash['genre'] == %w[Crime Drama]
}.to_json
puts output_json

生成的JSON将是:

[{"rating":"9.3","title":"The Shawshank Redemption","genre":["Crime","Drama"]}]

如果要将数据写入文件,请使用File.write(...)

File.write(
  'output.json',
  output_json
)

JSON[json_data]是解析或生成JSON的快捷方式。如果你传入一个字符串,它会假设你想通过解析它来创建该字符串的Ruby对象。如果你传递一个数组或一个哈希,它将序列化它并输出一个字符串。

File.write继承自IO,可以轻松(过度)写入文件。

  

在比较数组时也要排序,因此[1, 2]不等于[2, 1] ...

这是真的。如果值来自一个表单,或者由程序员控制的其他源,那么这个顺序是已知并强制执行的,这不是问题。在处理订单或案例可能不同的数组时,它会崩溃:

['a', 'b'] == ['a', 'b'] # => true
['a', 'b'] == ['b', 'a'] # => false

至于订单何时变化,比较可能会稍微改变并仍然有效:

(['a', 'b'] - ['a', 'b']).empty? # => true
(['a', 'b'] - ['b', 'a']).empty? # => true

案例可能有所不同,但可以通过规范化和更多代码轻松处理:

[['A', 'b'], ['a', 'b']].map { |ary| ary.map(&:downcase) }.inject(:-).empty? # => true
[['A', 'b'], ['B', 'a']].map { |ary| ary.map(&:downcase) }.inject(:-).empty? # => true