Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Sinatra, how to render json?

Tags:

ruby

sinatra

I find it very weird that this is OK:

  get '/initialize' do
    # ok 
    json foo: 'bar'
  end 

Yet this causes an error:

  get '/initialize' do
    json { foo: 'bar' }   # error! 
  end 

syntax error, unexpected ':', expecting '}' (SyntaxError)

Why?

How can I write the code like :

  get '/initialize' do
    json { 
         item1: { 
             item2: {
                 item3: 'ok'
             }
         } 
    }

  end 
like image 615
Siwei Avatar asked Oct 16 '25 04:10

Siwei


2 Answers

Because the latter case assumes you're calling json method with a block, and foo: 'bar' is an invalid statement. I.e.

json { foo: 'bar' }

is parsed in (almost) the same way as

json do
  foo: 'bar'
end

which is nonsense. ("almost" because the priority of braces and do...end differ a bit; not that it matters in this case.)

The former case assumes foo: 'bar' is a named argument, and is converted into a Hash. json({ foo: 'bar' }) would make it explicit that you're passing a Hash, and not writing a block. Thus, the following is the correct syntax for what you are trying to write:

get '/initialize' do
  json({ 
       item1: { 
           item2: {
               item3: 'ok'
           }
       } 
  })
end 

You can also use the keyword approach (though I find it's less readable):

get '/initialize' do
  json item1: { 
           item2: {
               item3: 'ok'
           }
       }
end 
like image 64
Amadan Avatar answered Oct 18 '25 20:10

Amadan


It works for me:

get '/songs' do
    content_type :json
    { song: "Wake me Up" }.to_json
end
like image 20
Eduardo Garcia Avatar answered Oct 18 '25 22:10

Eduardo Garcia