在我的应用程序中,我有一个 Controller ,该 Controller 对作为JSON接收的请求执行若干操作,但有时我会以x-www-form-urlencoded接收请求。
我想在 Controller Action 开始时将其转换为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"
# }

关于ruby - 将x-www-form-urlencoded转换为json,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/30593585/

10-09 01:53