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.

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.