ruby-on-rails Rails如何迭代JSON字段

iovurdzv  于 2023-02-01  发布在  Ruby
关注(0)|答案(1)|浏览(209)

我试着玩DALL·E2,我试着做的只是简单地调用他们的图像创建API,并使用他们返回的图像URL显示图像。
我一直在考虑如何根据JSON响应在网页上显示图像。
我所做的是将响应保存在ImageRequest模型的JSON属性中。
我的代码如下所示:

def new
    @image_request = ImageRequest.new
  end

  def create
    @image_request = ImageRequest.new(image_request_params)
    client = OpenAI::Client.new(access_token: "my_key")
    response = client.images.generate(parameters: { prompt: @image_request.prompt, n: @image_request.versions })
    @image_request.urls = response
    
    respond_to do |format|
      if @image_request.save
        format.html { redirect_to image_request_url(@image_request), notice: "Image request was successfully created." }
        format.json { render :show, status: :created, location: @image_request }
      else
        format.html { render :new, status: :unprocessable_entity }
        format.json { render json: @image_request.errors, status: :unprocessable_entity }
      end
    end
  end

  def show
    @image_request = ImageRequest.find(params[:id])
  end

但我试图确定的是如何解析和迭代JSON并显示图像?

# in psuedo code what I'm trying to do:
   <% images.each do |i| %>
      <%= image_tag "url" %>
    <% end %>

这就是OpenAI的回应:

{
  "created": 1674850160,
  "data": [
    {
      "url": "https://oaidalleapiprodscus.blob.core.windows.net/private/...."
    },
    {
      "url": "https://oaidalleapiprodscus.blob.core.windows.net/private/..."
    }
  ]
}

当我查看@image_request.urls中JSON属性(创建后)中的存储值时,它是:

{"created"=>1674850160, "data"=>[{"url"=>"https://oaidalleapiprodscus.blob.core.windows.net..."}, {"url"=>"https://oaidalleapiprodscus.blob.core.windows.net/private/..."}]}

我已经研究过这些SO问题并进行了实验,但我可以找出如何遍历返回的data.url。
Iterating over JSON in Rails
How do I parse JSON with Ruby on Rails?
Access JSONB fields as normal ActiveRecord attributes
Iterating over JSON in Rails
Loop through API response with .each

n6lpvg4x

n6lpvg4x1#

如果response{"created"=>1674850160, "data"=>[{"url"=>"https://oaida...,那么JSON已经被解析为Ruby数据结构,然后需要将其转换为URL列表。
从“data”数组的哈希中取出每个“url”值。

@image_request.urls = response["data"].pluck("url")

现在你有了一个可以迭代的URL数组。

<% image_request.urls.each do |url| %>
      <%= image_tag(url) %>
    <% end %>

相关问题