【发布时间】:2015-07-15 01:51:30
【问题描述】:
我有一个包含 647 个 JSON 对象的数组,我想提取每个对象并将它们一个一个地输入到 API 的请求正文中。 API 将仅接受每个 JSON 对象,每个对象都有单独的 HTTP 请求。我该怎么做?
到目前为止,这是我在 Ruby 中使用 HTTParty gem 的基本 each 块:
require "json"
require "httparty"
restaurants = JSON.parse File.read('pretty-regex2.json')
new_rest_variable = restaurants.each do |restaurant|
end
response = HTTParty.post("https://api.example/placeholder",
{
:body => new_rest_variable.to_json,
:headers => { "Content-Type" => "text", "Accept" => "application/x-www-form-urlencoded", "Authorization" => "token example-placeholder" }
})
puts response.body
puts response.code
puts response.message
647 中包含在数组方括号中的 4 个“餐厅对象”示例:
[
{
"id": "223078",
"name": "3 South Place",
"phone": "+442032151270",
"email": "3sp@southplacehotel.com",
"website": "",
"location": {
"latitude": 51.5190536,
"longitude": -0.0871038,
"address": {
"line1": "3 South Place",
"line2": "",
"line3": "",
"postcode": "EC2M 2AF",
"city": "London",
"country": "UK"
}
}
},
{
"id": "210071",
"name": "5th View Bar & Food",
"phone": "+442077347869",
"email": "waterstones.piccadilly@elior.com",
"website": "http://www.5thview.com",
"location": {
"latitude": 51.5089594,
"longitude": -0.1359897,
"address": {
"line1": "Waterstone's Piccadilly",
"line2": "203-205 Piccadilly",
"line3": "",
"postcode": "W1J 9HA",
"city": "London",
"country": "UK"
}
}
},
{
"id": "239971",
"name": "65 & King",
"phone": "+442072292233",
"email": "hello@65king.com",
"website": "http://www.65king.com/",
"location": {
"latitude": 51.5152533,
"longitude": -0.1916538,
"address": {
"line1": "65 Westbourne Grove",
"line2": "",
"line3": "",
"postcode": "W2 4UJ",
"city": "London",
"country": "UK"
}
}
},
{
"id": "131543",
"name": "Abbey",
"phone": "+442079682400",
"email": "info@abbey-bar.co.uk",
"website": "http://www.abbey-bar.co.uk",
"location": {
"latitude": 51.51241,
"longitude": -0.0751462,
"address": {
"line1": "St Clare House",
"line2": "30-33 Minories",
"line3": "",
"postcode": "EC3N 1DD",
"city": "London",
"country": "UK"
}
}
}
]
【问题讨论】: