In my app I have controller which perform several operation on request received as JSON, but sometimes I receive request as x-www-form-urlencoded.
I would like to convert it to JSON at begining of controller action.
For example I would like to convert:
%7B%0D%0A++%22action%22%3A+%22new_pet%22%2C%0D%0A++%22content%22%3A+%7B%0D%0A++++%220%22%3A+%7B%0D%0A++++++%22name%22%3A+%22Amigo%22%2C%0D%0A++++++%22sex%22%3A+%22male%22%2C%0D%0A++++++%22owner%22%3A+%227449903%22%2C%0D%0A++++++%22type%22%3A+%22dog%22%0D%0A++++%7D%0D%0A++%7D%2C%0D%0A++%22controller%22%3A+%22animal%22%0D%0A%7D
to:
{
"action": "new_pet",
"content": {
"0": {
"name": "Amigo",
"sex": "male",
"owner": "7449903",
"type": "dog"
}
},
"controller": "animal"
}
This can actually be done in Ruby without the need to involve Rails using the URI
module. Here is an example using your x-www-form-data
require 'uri'
FORM_DATA = '%7B%0D%0A++%22action%22%3A+%22new_pet%22%2C%0D%0A++%22content%22%3A+%7B%0D%0A++++%220%22%3A+%7B%0D%0A++++++%22name%22%3A+%22Amigo%22%2C%0D%0A++++++%22sex%22%3A+%22male%22%2C%0D%0A++++++%22owner%22%3A+%227449903%22%2C%0D%0A++++++%22type%22%3A+%22dog%22%0D%0A++++%7D%0D%0A++%7D%2C%0D%0A++%22controller%22%3A+%22animal%22%0D%0A%7D'
decoded_form = URI.decode_www_form(FORM_DATA)
json = decoded_form[0][0]
puts json
# =>
# {
# "action": "new_pet",
# "content": {
# "0": {
# "name": "Amigo",
# "sex": "male",
# "owner": "7449903",
# "type": "dog"
# }
# },
# "controller": "animal"
# }
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