Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting x-www-form-urlencoded to json

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"
}
like image 383
Gregy Avatar asked Jun 02 '15 10:06

Gregy


1 Answers

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"
# }
like image 117
Eli Sadoff Avatar answered Jun 19 '23 18:06

Eli Sadoff