0

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.

yellowreign
  • 3,528
  • 8
  • 43
  • 80

1 Answers1

1

because "provider" is an array.

it should be accessed with index.

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

same goes with "value".

Fernand
  • 1,293
  • 1
  • 10
  • 18
  • Sorry, I should have mentioned that I did try that based on https://stackoverflow.com/questions/20790499/no-implicit-conversion-of-string-into-integer-typeerror. I made it 'publisher: news['provider'][0]['name'],' but I get the same error. I'll add that to the question. – yellowreign Apr 07 '20 at 01:01
  • what is the output when you post [:provider]? – Fernand Apr 07 '20 at 01:06
  • If I do `puts news['provider'}`, I get {"_type"=>"Organization", "name"=>"UPI.com", "image"=>{"thumbnail"=>{"contentUrl"=>"https://www.bing.com/th?id=AR_d88c5b6fb27b317026ee10242444fb8b&pid=news"}}} – yellowreign Apr 07 '20 at 01:14
  • When I change `publisher: news['provider'][0]['name']` to either`publisher: news[0]['provider'][0]['name']` or `publisher: [:value][0]['provider'][0]['name']`, I get Resource creation error: undefined method `[]' for nil:NilClass. – yellowreign Apr 07 '20 at 01:19
  • you need to use symbol to all keys [:value][0][:provider][0][:name] – Fernand Apr 07 '20 at 01:21
  • Hmmm. Even when I do `publisher: [:value][0][:provider][0][:name]`, I get the same error. – yellowreign Apr 07 '20 at 01:31
  • what is the output if you try this: publisher: news[:provider] – Fernand Apr 07 '20 at 01:35
  • I get {"_type"=>"Organization", "name"=>"UPI.com", "image"=>{"thumbnail"=>{"contentUrl"=>"bing.com/th?id=AR_d88c5b6fb27b317026ee10242444fb8b&pid=news"}}} – yellowreign Apr 07 '20 at 01:37
  • and this one... publisher: [:provider][0] – Fernand Apr 07 '20 at 01:45
  • puts [:provider][0] => `provider` – yellowreign Apr 07 '20 at 01:52
  • [:provider][0][:name] should work then... maybe you need to check if it has data: provider: [:provider][0].present? ? [:provider][0][:name] : "" – Fernand Apr 07 '20 at 02:06