将x-www-form-urlencoded转换为json

时间:2015-06-02 10:30:45

标签: ruby json ruby-on-rails-3

在我的应用程序中,我有控制器,它根据JSON收到请求执行多项操作,但有时我会收到x-www-form-urlencoded的请求。 我想在控制器动作开始时将其转换为JSON。

例如,我想转换:

%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

为:

{
  "action": "new_pet",
  "content": {
    "0": {
      "name": "Amigo",
      "sex": "male",
      "owner": "7449903",
      "type": "dog"
    }
  },
  "controller": "animal"
}

1 个答案:

答案 0 :(得分:0)

实际上,这可以在Ruby中完成,而无需使用URI模块参与Rails。这是使用您的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"
# }