0

I'm new to ruby on rails and I'm trying to manipulate the json data into another json format. I have this Controller,thats calls API service URL: https://api.publicapis.org/entries

class DemoController < ApplicationController
    def index
        demohelper = DemoHelper::APIService.new
        obj = JSON.parse(demohelper.getdata())
        @entrylist = obj['entries'].map do |e|
           e
        end
        render json:@entrylist
    end
end

below is the sample data from the entries array

API :   WeatherAPI
Description :   Weather API with other stuff like Astronomy and Geolocation API
Auth    :   apiKey
HTTPS   :   true
Cors    :   yes
Link    :   https://www.weatherapi.com/
Category    :   Weather

what I would like to return is

[{ api, desc }]

but when I use the code below

@entrylist = obj['entries'].map do |e|
  { :api => e.API , :desc => e.Description }
end

but I keep on getting error when I use the code above

enter image description here

-----UPDATE ----

I can actually use the rocket symbol by doing the field as "api" not :api as I previously used.

@entrylist = obj['entries'].map do |e|
  { "api"=> e["API"] , "desc"=> e["Description"] }
end

1 Answers1

2

Just need to reference the API/Description methods as keys, not methods:

@entrylist = obj['entries'].map do |e|
  { api: e["API"] , desc: e["Description"] }
end
Gavin Miller
  • 43,168
  • 21
  • 122
  • 188
  • thank you! That worked! May I ask, when should I use => instead of colon(:) ? I also noticed that when I do a multiline on the format it doesn't work – Reydan Gatchalian Sep 13 '22 at 19:13
  • @ReydanGatchalian great question. `=>` is legacy Ruby 1.9 syntax, typically you'll want to use the symbol keys `symbol: 'value'`. That said there are some cases where you can't do that. This SO post goes into details: https://stackoverflow.com/a/10004344/33226 – Gavin Miller Sep 13 '22 at 20:55