我有以下在 bash 中工作的:
curl -d "{ \"auth_token\": \"secret\", \"current\":"${COUNT}"}" http://lab:3030/widgets/connections
但是如果我在 Ruby 中尝试这个是失败的:
`curl -d "{\"auth_token\":\"secret\",\"current\":"#{count}"}" http://lab:3030/widgets/connections`
并得到这个错误信息:
JSON::ParserError - 746: unexpected token at '{auth_token:secret,current:4}':
Ruby 的输出在屏幕上看起来是正确的,但触发了 JSON 解析器错误。我还能检查什么?
我正在考虑使用像 curb-fu 这样的 gem,但无法弄清楚如何构建它以使其看起来与上面的 bash 一样。
谢谢。
最佳答案
您可以使用stdlib
的json
转换哈希:
require 'json'
{foo: "bar"}.to_json
#=> "{\"foo\":\"bar\"}"
和shellwords
构建命令:
require 'shellwords'
['curl', '-d', '{"foo":"bar"}', 'http://example.com/'].shelljoin
#=> "curl -d \\{\\\"foo\\\":\\\"bar\\\"\\} http://example.com/"
完整示例:
require 'json'
require 'shellwords'
data = {auth_token: secret, current: count}
`#{['curl', '-d', data.to_json, 'http://lab:3030/widgets/connections'].shelljoin}`
关于ruby - 在 bash 和 ruby 中使用 curl,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17919319/