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



在我的应用程序中,我有控制器,它对收到的请求执行几个操作作为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"
}

这实际上可以在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"
# }

相关内容

  • 没有找到相关文章

最新更新