【问题标题】:How to render content from nested json object in ruby on rails view如何在 ruby​​ on rails 视图中渲染嵌套 json 对象的内容
【发布时间】:2021-11-10 22:46:04
【问题描述】:

我正在尝试将来自 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(这是“heroimage”下的一级)。

【问题讨论】:

    标签: ruby-on-rails strapi httparty


    【解决方案1】:

    不应该是这样的

    @post[:heroimage][:url]
    

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

    工作?

    使用 ruby​​,您应该能够将键视为符号。并且 ruby​​ 不会在哈希中使用点表示法,因此您需要使用方括号。

    【讨论】:

    • 感谢 Corey,这足以让它发挥作用。最后我不得不做@post["heroimage"]["url"]
    【解决方案2】:

    您必须将响应从 json 转换为 Hash 并为此使用:

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-02
      • 1970-01-01
      • 1970-01-01
      • 2019-09-25
      相关资源
      最近更新 更多