简体   繁体   中英

How to render content from nested json object in ruby on rails view

I'm trying to render data from a API response (JSON) into my view.

For some reason i only can access the toplevel objects withouth any issues. BUt my knowledge is limited when it commes to retrieve the data from a nested object.

Woul appreciate if anybody can help me out.

controller.rb

require 'httparty'

class BlogController < ApplicationController

    include HTTParty

    def show
      id = params[:id]
      get("posts/#{id}")
    end

    def index
      get('posts')
    end

    private

    def get(path)
      @host = 'api.example.com'
      @blog = HTTParty.get('https://' + @host + '/' + path )
      @post = HTTParty.get('https://' + @host + '/' + path )
      
      return false if response.status != 200
      puts response.body
    end
end


view.html.erb

<p id="notice"><%= notice %></p>

<h2><%= @post["title"] %></h2>
<p><%= @post["description"] %></p>
<p><%= @post["content"] %></p>
<p><%= @post["heroimage.url"] %></p> <# This here is the problem how to render the url object which is part of "heroimage" parent

JSON response which i'm consuming:

{
  "id": 1,
  "title": "First Post",
  "description": "Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam",
  "content": "Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. \n\n![g-000261-g_W2615899_6-ktm-300-exc-637602315686776824.jpg](/uploads/g_000261_g_W2615899_6_ktm_300_exc_637602315686776824_a3b44fdf00.jpg)\n\n\nDuis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi. Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. ",
  "author": null,
  "created_at": "2021-10-28T21:31:10.445Z",
  "updated_at": "2021-11-10T17:54:36.175Z",
  "heroimage": {
    "id": 1,
    "name": "g-000261-g_W2615899_6-ktm-300-exc-637602315686776824.jpg",
    "alternativeText": "",
    "caption": "",
    "width": 2048,
    "height": 1536,
    "formats": {
      "large": {
        "ext": ".jpg",
        "url": "/uploads/large_g_000261_g_W2615899_6_ktm_300_exc_637602315686776824_a3b44fdf00.jpg",
        "hash": "large_g_000261_g_W2615899_6_ktm_300_exc_637602315686776824_a3b44fdf00",
        "mime": "image/jpeg",
        "name": "large_g-000261-g_W2615899_6-ktm-300-exc-637602315686776824.jpg",
        "path": null,
        "size": 184.83,
        "width": 1000,
        "height": 750
      },
      "small": {
        "ext": ".jpg",
        "url": "/uploads/small_g_000261_g_W2615899_6_ktm_300_exc_637602315686776824_a3b44fdf00.jpg",
        "hash": "small_g_000261_g_W2615899_6_ktm_300_exc_637602315686776824_a3b44fdf00",
        "mime": "image/jpeg",
        "name": "small_g-000261-g_W2615899_6-ktm-300-exc-637602315686776824.jpg",
        "path": null,
        "size": 50.69,
        "width": 500,
        "height": 375
      },
      "medium": {
        "ext": ".jpg",
        "url": "/uploads/medium_g_000261_g_W2615899_6_ktm_300_exc_637602315686776824_a3b44fdf00.jpg",
        "hash": "medium_g_000261_g_W2615899_6_ktm_300_exc_637602315686776824_a3b44fdf00",
        "mime": "image/jpeg",
        "name": "medium_g-000261-g_W2615899_6-ktm-300-exc-637602315686776824.jpg",
        "path": null,
        "size": 110.16,
        "width": 750,
        "height": 563
      },
      "thumbnail": {
        "ext": ".jpg",
        "url": "/uploads/thumbnail_g_000261_g_W2615899_6_ktm_300_exc_637602315686776824_a3b44fdf00.jpg",
        "hash": "thumbnail_g_000261_g_W2615899_6_ktm_300_exc_637602315686776824_a3b44fdf00",
        "mime": "image/jpeg",
        "name": "thumbnail_g-000261-g_W2615899_6-ktm-300-exc-637602315686776824.jpg",
        "path": null,
        "size": 10.56,
        "width": 208,
        "height": 156
      }
    },
    "hash": "g_000261_g_W2615899_6_ktm_300_exc_637602315686776824_a3b44fdf00",
    "ext": ".jpg",
    "mime": "image/jpeg",
    "size": 711.13,
    "url": "/uploads/g_000261_g_W2615899_6_ktm_300_exc_637602315686776824_a3b44fdf00.jpg",
    "previewUrl": null,
    "provider": "local",
    "provider_metadata": null,
    "created_at": "2021-11-10T16:22:27.152Z",
    "updated_at": "2021-11-10T16:22:27.169Z"
  }
}

As mentioned i'm trying to display the url (which is one level under "heroimage").

Shouldn't something like

@post[:heroimage][:url]

work?

With ruby, you should be able to treat the keys like a symbol. and ruby won't use dot notation in a hash so you would need to use square brackets.

You will have to convert response from json to Hash and for that use this:

parsed_response = JSON.parse(response.body)

After that it is just a hash so you can access simply like following:

parsed_response['heroimage']['url']

I would recommend to use dig here

parsed_response.dig('heroimage', 'url')

If you want a structured object then I would recommend to use RecursiveOpenStruct it will make all fields as nested object attributes

structured = RecursiveOpenStruct.new(parsed_response)
structured.heroimage.url

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM