Извлечение значения из JSON через API в ruby - PullRequest
0 голосов
/ 16 января 2020

Я получаю ответ от API, но не могу получить результат, как указано ниже:

[
 {
 "description": "...................",
 "pricePerUnit": "..........",
 "effectiveDate": "............."
 "location": "................"
 }
]

Я пробовал следующий код:

require 'httparty'
class ApiTest
  def self.required_data
    url ="https://pricing.us-east-1.amazonaws.com/offers/v1.0/aws/AmazonCloudFront/current/index.json"
    response = HTTParty.get(url, :query => {},:headers => {}
  )
    result = JSON.parse(response.body)
    required_json = {}
    required_json["price_publish_date"] = result["publicationDate"]
    table_data = {}

   result["terms"]["OnDemand"].each do |value|
    table_data["table_data"] = value[1]
   end
 end
end

puts ApiTest.required_data

Я могу извлечь ниже:

{"table_data"=>{"CYHNW9MJYBF8UUJY.JRTCKXETXF"=>{"offerTermCode"=>"JRTCKXETXF", "sku"=>"CYHNW9MJYBF8UUJY", "effectiveDate"=>"2019-12-01T00:00:00Z", "priceDimensions"=>{"CYHNW9MJYBF8UUJY.JRTCKXETXF.6YS6EN2CT7"=>{"rateCode"=>"CYHNW9MJYBF8UUJY.JRTCKXETXF.6YS6EN2CT7", "description"=>"$6.0E-7  per Request for Lambda-Edge-Request in AWS GovCloud (US-East)", "beginRange"=>"0", "endRange"=>"Inf", "unit"=>"Request", "pricePerUnit"=>{"USD"=>"0.0000006000"}, "appliesTo"=>[]}}, "termAttributes"=>{}}}}

Все данные доступны в приведенном выше результате.

Пожалуйста, наведите меня, чтобы я мог двигаться вперед.

1 Ответ

0 голосов
/ 17 января 2020

Я быстро взглянул на ответ от https://pricing.us-east-1.amazonaws.com/offers/v1.0/aws/AmazonCloudFront/current/index.json

Структура полученного ответа будет выглядеть следующим образом:

type AutoGenerated struct {
  FormatVersion   string    `json:"formatVersion"`
  Disclaimer      string    `json:"disclaimer"`
  OfferCode       string    `json:"offerCode"`
  Version         string    `json:"version"`
  PublicationDate time.Time `json:"publicationDate"`
  Products        struct {
    RN2BPS8XT2GYJ4UF struct {
      Sku           string `json:"sku"`
      ProductFamily string `json:"productFamily"`
      Attributes    struct {
        Servicecode      string `json:"servicecode"`
        Location         string `json:"location"`
        LocationType     string `json:"locationType"`
        Group            string `json:"group"`
        GroupDescription string `json:"groupDescription"`
        Usagetype        string `json:"usagetype"`
        Operation        string `json:"operation"`
        Servicename      string `json:"servicename"`
      } `json:"attributes"`
    } `json:"RN2BPS8XT2GYJ4UF"`
  } `json:"products"`
  Terms struct {
    OnDemand struct {
      RN2BPS8XT2GYJ4UF struct {
        RN2BPS8XT2GYJ4UFJRTCKXETXF struct {
          OfferTermCode   string    `json:"offerTermCode"`
          Sku             string    `json:"sku"`
          EffectiveDate   time.Time `json:"effectiveDate"`
          PriceDimensions struct {
            RN2BPS8XT2GYJ4UFJRTCKXETXF6YS6EN2CT7 struct {
              RateCode     string `json:"rateCode"`
              Description  string `json:"description"`
              BeginRange   string `json:"beginRange"`
              EndRange     string `json:"endRange"`
              Unit         string `json:"unit"`
              PricePerUnit struct {
                USD string `json:"USD"`
              } `json:"pricePerUnit"`
              AppliesTo []interface{} `json:"appliesTo"`
            } `json:"RN2BPS8XT2GYJ4UF.JRTCKXETXF.6YS6EN2CT7"`
          } `json:"priceDimensions"`
          TermAttributes struct {
          } `json:"termAttributes"`
        } `json:"RN2BPS8XT2GYJ4UF.JRTCKXETXF"`
      } `json:"RN2BPS8XT2GYJ4UF"`
    } `json:"OnDemand"`
  } `json:"terms"`
}

Похоже на ваш Основной вопрос здесь заключается в том, как манипулировать ха sh в Ruby.

. Возможно, вы захотите перебрать товары следующим образом:

parsed = JSON.parse(response.body)
result = []
# You are using only the product key to collect the corresponding terms
parsed['terms']['OnDemand'].each do |_product_key, offers|
  offers.each do |_offer, details|
    effective_date = details['effectiveDate']
    details['priceDimensions'].each do |_name, dimension|
      result << { 'description' => dimension['description'], 'effectiveDate' => effective_date } # more fields according to your need
    end
  end
end
# If you need the product key for a more complex aggregation, you may consider
# parsed['products'].keys and iterate explicitly over terms
result

Вы можете немного пересмотреть, как перебрать хеш-таблицу в ruby и узнать, как найти вложенные значения.

Наверняка эта структура ответа на самом деле не является стандартной и довольно сложной для манипулирования

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...