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

Gre*_*egy 5 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
Run Code Online (Sandbox Code Playgroud)

至:

{
  "action": "new_pet",
  "content": {
    "0": {
      "name": "Amigo",
      "sex": "male",
      "owner": "7449903",
      "type": "dog"
    }
  },
  "controller": "animal"
}
Run Code Online (Sandbox Code Playgroud)

Eli*_*off 1

这实际上可以在 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"
# }
Run Code Online (Sandbox Code Playgroud)