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
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
It works for me:
get '/songs' do
content_type :json
{ song: "Wake me Up" }.to_json
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With