ruby-on-rails - 如何使用 HTTParty 提取 JSON 数组字段?
问题描述
我正在使用 FOOD2FORK api 在 ruby 中使用 HTTParty 提取数据。
我的代码:
require 'httparty' #Note : This file is in the models >> filename.rb
#Don't need to require when using bundler
#Restful Web Services
#1. Base URI 2. Support XML or JSON 3. Support HTTP operations (GET, POST)
#Think of web at MVC : website you can get resources in any format
#HTTParty parses XML or JSON for you (like your browser - it's a client). Parses into a Ruby hash or array
class Recipe
include HTTParty
ENV["FOOD2FORK_KEY"] = "5b6b74c6cc0fa9dc23871a7ae753f6c7"
base_uri "https://food2fork.com/api" #Same across most requests
default_params key: ENV["FOOD2FORK_KEY"], fields: "image_url" #defaults, like API developer key #fields: "image_url, source_url, title",
format :json #Tell it which format data comes in
#q:"search" request parameter
def self.for (keyword)
#class method called for which takes in a term
get("/search", query: {q: keyword})["recipes"] #get is method provided by HTTParty
#returns array where each element in the array is a hash
end
pp Recipe.for "chocolate"
end
它让我回来了
[
{
"publisher"=>"BBC Good Food",
"f2f_url"=>"http://food2fork.com/view/9089e3",
"title"=>"Cookie Monster cupcakes",
"source_url"=>"http://www.bbcgoodfood.com/recipes/873655/cookie-monster-cupcakes",
"recipe_id"=>"9089e3",
"image_url"=>"http://static.food2fork.com/604133_mediumd392.jpg",
"social_rank"=>100.0,
"publisher_url"=>"http://www.bbcgoodfood.com"
}
]
但我只想提取它,image_url
甚至使用field
它提取整个数据集知道如何只提取 image_url 吗?
PS 你可以在这里查看 JSON 的格式 - http://food2fork.com/api/search?key=65987bf1f4b22007c365c243f5670f35&q=shredded%20chicken
解决方案
下面的代码应该可以工作
response = your response from API
response_data = JSON.parse(response.body).with_indifferent_access
response_data['recipes'].each do |recipe|
puts recipe['image_url'] # image_url of block
end
推荐阅读
- angular - 来自指令输入数组的角度样式 viewContainerRef
- sharepoint - 如何使用 CSOM 禁用 SharePoint 2013 警报
- azure-pipelines - .Net 5 - Azure Pipeline - 找不到指定的 SDK 'Microsoft.NET.Sdk.BlazorWebAssembly'
- node.js - Express JS 条件路由 - 如何路由多个支付网关?
- r - 将一列转换为字符
- mysql - 如何使用 MySql 中的嵌套元素生成 JSON
- php - 修剪 unicode 空格 PHP
- java - 如何使用具有域限制的谷歌 API 使用谷歌表格
- c# - 使用特定时区而不是服务器时区
- android - 我可以以编程方式打开我自己的应用程序吗?