2

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?

2 Answers 2

2

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
Sign up to request clarification or add additional context in comments.

Comments

0

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

results["a"]
results["b"]
...

2 Comments

I get nil when I try and access it like that.
@jmcharnes try removing the symbolize_names parameter.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.