Question

I'm sending an object from Javascript to a Sinatra POST route. I'm using the 'stringify' method to convert my js object to JSON. The JSON being sent is like so (according to the dev tools in chrome):

{"a":1,"b":2,"c":"3"}:

I have my route in Sinatra setup like so:

post '/results' do
    results = JSON.parse(params.to_json, symbolize_names: true)
end

I can't figure how to access the keys in Ruby once I parse the JSON. Is there a better way to do so, am I missing something?

Was it helpful?

Solution

I believe that if you are sending the JSON in the POST body - you should access it from request.body, and not from params (see this question: How to parse JSON request body in Sinatra just once and expose it to all routes?):

post '/results' do
  request.body.rewind
  results = JSON.parse(request.body.read, symbolize_names: true)
end

OTHER TIPS

You should be able to access it like an associative array:

results["a"]
results["b"]
...
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top