Home > OS >  Rails How Can I Iterate Over JSON Field
Rails How Can I Iterate Over JSON Field

Time:01-28

I'm trying to play around with DALL·E 2 and what I'm trying to do is simply call their image creation API and display the images using the image URLs they return.

I'm getting stuck on how to show the images on my web page based on the JSON response.

What I've done is save the response in a JSON attribute for my ImageRequest model.

So my code looks like this:

  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

But what I'm trying to determine is how can I parse and iterate the JSON and show the images?

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

This is what the OpenAI response is:

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

When I look at the stored value in the JSON attribute (after create) in @image_request.urls, it's:

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

I've looked at these SO questions and experimented, but I can figure out how to just iterate through the data.url(s) returned.

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

CodePudding user response:

If response is {"created"=>1674850160, "data"=>[{"url"=>"https://oaida... then the JSON has already been parsed for you into a Ruby data structure. You then need to turn that into a list of URLs.

Extract each "url" value from the Hashes in the "data" Array.

@image_request.urls = response["data"].map { |d| d["url"] }

Now you have an Array of URLs which you can iterate through.

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