如何在 rails 视图上呈现 ruby 中嵌套 json 对象的内容

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

我正在尝试将来自 API 响应 (JSON) 的数据呈现到我的视图中。

出于某种原因,我只能毫无问题地访问顶级对象。但是当涉及到从嵌套对象中检索数据时,我的知识是有限的。

如果有人能帮助我,我将不胜感激。

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 我正在消费的响应:

{
  "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"
  }
}

如前所述,我正在尝试显示 url(这是“英雄形象”下的一层)。

不应该是

@post[:heroimage][:url]

@post['heroimage']['url']

工作?

使用 ruby,您应该能够像对待符号一样对待按键。并且 ruby 不会在散列中使用点符号,因此您需要使用方括号。

您必须将响应从 json 转换为哈希,为此使用:

parsed_response = JSON.parse(response.body)

在那之后它只是一个散列,所以你可以像下面这样简单地访问:

parsed_response['heroimage']['url']

我建议在这里使用 dig

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

如果你想要一个结构化对象,那么我建议使用 RecursiveOpenStruct 它会将所有字段作为嵌套对象属性

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