我有一个647 JSON对象的数组,我想提取每个对象并将它们一个接一个地提供给API的请求体。 API将仅接受每个JSON对象,并为每个对象分别提供单独的HTTP请求。我该怎么做?
这是我到目前为止使用Ruby中的基本每个块和HTTParty gem:
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
4"餐厅对象"用647:
中的数组方括号括起来[
{
"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"
}
}
}
]
答案 0 :(得分:2)
尝试:
require "json"
require "httparty"
restaurants = JSON.parse File.read('pretty-regex2.json')
restaurants.each do |restaurant|
response = HTTParty.post("https://api.example/placeholder",
{
:body => restaurant.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
end