在 Sinatra 应用程序中解析请求 JSON
Parsing request JSON in Sinatra app
我在解析来自 Sinatra 应用程序请求的 JSON 时遇到了一些困难:
response = JSON.pretty_generate(request.env)
reply = response["rack.request.form_hash"]
返回结果:
rack.request.form_hash
作为字符串而不仅仅是响应的相关部分:
{...
"rack.request.form_hash": {
"token": "token",
"team_id": "team",
"team_domain": "teamname",
"service_id": "service",
"channel_id": "channel",
"channel_name": "testing-webhooks",
"timestamp": "1424480976.000910",
"user_id": "U029W1WF2",
"user_name": "myusername",
"text": "checkeverything",
"trigger_word": "checkeverything"
},
...}
它在我试图解析的 JSON 请求对象中。当我使用:
response["rack.request.form_hash"]["user_name"]
没有返回任何内容。我的日志中返回以下内容:
App 1662 stdout:
App 1640 stderr: JSON::ParserError - 746: unexpected token at 'No text specified':
所以看起来它没有正确迭代,或者可能无法访问它。
我查看了其他文档和其他帖子,但没有找到对我有用的东西,但我肯定忽略了一些东西,但我不确定是什么。
在对 Sinatra 的请求中解析这个嵌套数组的最佳方法是什么?
这应该可以解决问题:
res = JSON.parse( JSON.generate(request.env) )
res.class
# => Hash
res["rack.url_scheme"]
# => http
原因是JSON.generate只为字符串中的对象和数组生成JSON语法。然后你需要将生成的 JSON 字符串解析成 Ruby 中的散列和 JSON.parse.
我在解析来自 Sinatra 应用程序请求的 JSON 时遇到了一些困难:
response = JSON.pretty_generate(request.env)
reply = response["rack.request.form_hash"]
返回结果:
rack.request.form_hash
作为字符串而不仅仅是响应的相关部分:
{...
"rack.request.form_hash": {
"token": "token",
"team_id": "team",
"team_domain": "teamname",
"service_id": "service",
"channel_id": "channel",
"channel_name": "testing-webhooks",
"timestamp": "1424480976.000910",
"user_id": "U029W1WF2",
"user_name": "myusername",
"text": "checkeverything",
"trigger_word": "checkeverything"
},
...}
它在我试图解析的 JSON 请求对象中。当我使用:
response["rack.request.form_hash"]["user_name"]
没有返回任何内容。我的日志中返回以下内容:
App 1662 stdout:
App 1640 stderr: JSON::ParserError - 746: unexpected token at 'No text specified':
所以看起来它没有正确迭代,或者可能无法访问它。
我查看了其他文档和其他帖子,但没有找到对我有用的东西,但我肯定忽略了一些东西,但我不确定是什么。
在对 Sinatra 的请求中解析这个嵌套数组的最佳方法是什么?
这应该可以解决问题:
res = JSON.parse( JSON.generate(request.env) )
res.class
# => Hash
res["rack.url_scheme"]
# => http
原因是JSON.generate只为字符串中的对象和数组生成JSON语法。然后你需要将生成的 JSON 字符串解析成 Ruby 中的散列和 JSON.parse.