0

I am making a call to an external API and get the following response data in JSON.

{
  "count": 1,
  "styles": [
    {
      "vehicle_id": "400882961",
      "style": "AWD Titanium 4dr Sedan"
    }
  ]
}

I am wondering how I can use the data in my view. I am using @details to represent my data. If I put @details.inspect in my view I give me the data as you see it here.

I'd like to be able to put the vehicle_id and style info in my view.

Completely new to Rails so I am little lost. Any help would be greatly appreciated.

sethvargo
  • 26,739
  • 10
  • 86
  • 156
Mark Datoni
  • 484
  • 1
  • 5
  • 10

1 Answers1

1

The first thing you need to do is parse the JSON. This functionality is part of the Ruby language as of 1.9+:

@api_response = JSON.parse(data)

This converts the raw JSON (a string) into a queryable Ruby data structure (a hash). Next, you lookup items in the hash. Note that styles is an array, so there could be more than one vehicle_id returned.

Here are some examples of how you could use this in your template:

<%= @api_response["styles"].first["vehicle_id"] %>

Or, if you want to iterate over all styles:

<% @api_response["styles"].each do |h| %>
  <%= h["vehicle_id"] %>: <%= h["style"] %>
<% end %>

You can read more about Ruby hashes in the Ruby docs.

sethvargo
  • 26,739
  • 10
  • 86
  • 156