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?

jmcharnes
  • 707
  • 12
  • 23

2 Answers2

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
Community
  • 1
  • 1
Uri Agassi
  • 36,848
  • 14
  • 76
  • 93
0

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

results["a"]
results["b"]
...
TheAJ
  • 10,485
  • 11
  • 38
  • 57