0
votes

My Rails app is reading in JSON from a Bing API, and creating a record for each result. However, when I try to save one of the nested JSON attributes, I'm getting Resource creation error: no implicit conversion of String into Integer.

The JSON looks like this:

{
  "Demo": {
    "_type": "News",
    "readLink": "https://api.cognitive.microsoft.com/api/v7/news/search?q=european+football",
    "totalEstimatedMatches": 2750000,
    "value": [
      {
        "provider": [
          {
            "_type": "Organization",
            "name": "Tuko on MSN.com"
          }
        ],
        "name": "Hope for football fans as top European club resume training despite coronavirus threat",
        "url": "https://www.msn.com/en-xl/news/other/hope-for-football-fans-as-top-european-club-resume-training-despite-coronavirus-threat/ar-BB12eC6Q",
        "description": "Bayern have returned to training days after leaving camp following the outbreak of coronavirus. The Bundesliga is among top European competitions suspended."
        }
      }

The attribute I'm having trouble with is [:provider][:name].

Here's my code:

  def handle_bing
    @terms = get_terms

    @terms.each do |t|
      news = get_news(t)

      news['value'].each do |n|
        create_resource(n)
      end
    end
  end  

  def get_terms
    term = ["European football"]
  end

  def get_news(term)
    accessKey = "foobar"
    uri  = "https://api.cognitive.microsoft.com"
    path = "/bing/v7.0/news/search"

    uri = URI(uri + path + "?q=" + URI.escape(term))
    request = Net::HTTP::Get.new(uri)
    request['Ocp-Apim-Subscription-Key'] = accessKey

    response = Net::HTTP.start(uri.host, uri.port, :use_ssl => uri.scheme == 'https') do |http|
      http.request(request)
    end

    response.each_header do |key, value|
       # header names are coerced to lowercase
       if key.start_with?("bingapis-") or key.start_with?("x-msedge-") then
          puts key + ": " + value
       end
    end

    return JSON(response.body)
  end


  def create_resource(news)
    Resource.create(
      name: news['name'],
      url: news['url'],
      description: news['description'],
      publisher: news['provider']['name']
    )
  end

I looked at these questions, but they didn't help me:

Extract specific field from JSON nested hashes

No implicit conversion of String into Integer (TypeError)?

Why do I get "no implicit conversion of String into Integer (TypeError)"?

UPDATE: I also tried updating the code to:

publisher: news['provider'][0]['name'], but I received the same error.

1

1 Answers

0
votes

because "provider" is an array.

it should be accessed with index.

[:value][0][:provider][0][:name]

same goes with "value".