我试图从他们的API中提取NY Times Bestseller信息,然后用Ruby解析并打印出所有漂亮的信息。
出于某种原因,它无法正常工作。可能是因为我是个白痴?请善待。我是初学者。
runner.rb
require 'json'
require 'rest-client'
require_relative 'books.rb'
result = RestClient.get('http://api.nytimes.com/svc/books/v2/lists/Combined-Print-and-E-Book-Fiction.json?&offset=&sortby=&sortorder=&api-key=**********************')
parsed = JSON.parse result
books = parsed["results"].each do |results_hash|
results_hash["book_details"].collect do |s|
Bestseller.new s["title"], s["description"], s["author"]
end
end
puts "Here's some books"
books.each do |infos|
puts infos
end
books.rb
class Bestseller
def initialize title, description, author
@title = title
@description = description
@author = author
end
end
好的,所以接受了以下建议。错误消失了。但现在书籍变量显示的是我不想要的东西。我只想要标题,描述,作者。
[{"list_name"=>"Combined Print and E-Book Fiction", "display_name"=>"Combined Print & E-Book Fiction", "updated"=>"WEEKLY", "bestsellers_date"=>"2013-11-02", "published_date"=>"2013-11-17", "list_image"=>"9781101626368.jpg", "normal_list_ends_at"=>15, "rank"=>1, "rank_last_week"=>0, "weeks_on_list"=>1, "asterisk"=>0, "dagger"=>0, "isbns"=>[{"isbn10"=>"0425259854", "isbn13"=>"9780425259856"}], "book_details"=>[{"title"=>"DARK WITCH", "description"=>"In the first book of the Cousins O'Dwyer trilogy, Iona Sheehan moves to Ireland to investigate her family's history.", "contributor"=>"by Nora Roberts", "author"=>"Nora Roberts"
如果您想/需要查看原始json数据,请点击此处:http://api.nytimes.com/svc/books/v2/lists/Combined-Print-and-E-Book-Fiction.json?&offset=&sortby=&sortorder=&api-key=6504A37DEA8BB8DC7B13807A5DA44D16:17:68383866
添加哈希示例:
{"status"=>"OK",
"copyright"=>"Copyright (c) 2013 The New York Times Company. All Rights Reserved.",
"num_results"=>25,
"last_modified"=>"2013-11-08T13:15:36-05:00",
"results"=>
[
{"list_name"=>"Combined Print and E-Book Fiction",
"display_name"=>"Combined Print & E-Book Fiction",
"updated"=>"WEEKLY",
"bestsellers_date"=>"2013-11-02",
"published_date"=>"2013-11-17",
"list_image"=>"9781101626368.jpg",
"normal_list_ends_at"=>15, "
rank"=>1,
"rank_last_week"=>0,
"weeks_on_list"=>1,
"asterisk"=>0,
"dagger"=>0,
"isbns"=>
[
{"isbn10"=>"0425259854",
"isbn13"=>"9780425259856"}
],
"book_details"=>
[
{"title"=>"DARK WITCH",
"description"=>"In the first book of the Cousins O'Dwyer trilogy, Iona Sheehan moves to Ireland to investigate her family's history.",
"contributor"=>"by Nora Roberts",
"author"=>"Nora Roberts",
答案 0 :(得分:1)
看起来你并没有正确地解析结果。 results
是一个包含密钥为book_details
的哈希的数组。所以,你想要的东西是:
books = parsed["results"].each do |results_hash|
results_hash["book_details"].map do |book_details_hash|
book = Bestseller.new book_details_hash["title"], book_details_hash["description"], book_details_hash["author"]
book.save!
end
end
上面的添加将Bestseller
设置为变量簿,然后保存。另一种方法是使用Bestseller.create
代替Bestseller.new
。