gpt4 book ai didi

ruby-on-rails - 葡萄,将 JSON 作为参数发送

转载 作者:数据小太阳 更新时间:2023-10-29 07:26:42 26 4
gpt4 key购买 nike

我的 Grape API 接受 json 格式,我有接受 JSON 作为参数的方法:

desc 'JSON test'
params do
requires :json, type: JSON
end
post :json_test do
json = params[:json]
{result: json}
end

当我通过 postman 发出请求时,参数是原始的 application/json 内容类型:

{
"json": {"test": "test"}
}

当我发送这个时,我收到错误信息:

"json is invalid"

但是,当我这样发送时:

{
"json": "{\"test\": \"test\"}"
}

它显示了正确的响应:

{
"result": {
"test": "test"
}
}

为什么会这样?当我创建 Hash 类型时,第一个变体起作用了,但是如果我想发送 Array 的哈希/jsons 呢?我知道 Grape 不支持 Array[Hash] 类型。

最佳答案

grape 在到达您的参数 block 之前解析 application/json 数据。


在此 block 中:

params do
requires :json, type: JSON
end

你告诉 grape 你的 :json 参数应该包含一个 JSON 字符串。

所以当你发送这个时:

{
"json": {"test": "test"}
}

json包含

{"test": "test"} 

这被视为一个散列,不是一个有效的 JSON 字符串,因此我们的错误。

但是当你发送这个

{
"json": "{\"test\": \"test\"}"
}

json包含

"{\"test\": \"test\"}"

这是一个有效的 JSON 字符串,然后它会很乐意为您解析为哈希。


如果你想用

{
"json": {"test": "test"}
}

在你的帖子请求中,你的参数 block 应该是这样的:

params do
requires :json, type: Hash #<-- Hash here instead of JSON since json data has already been parsed into a Hash
end

关于ruby-on-rails - 葡萄,将 JSON 作为参数发送,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36686659/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com