ruby - 在 bash 和 ruby​​ 中使用 curl

标签 ruby bash curl

我有以下在 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 一样。

谢谢。

最佳答案

您可以使用stdlibjson转换哈希:

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/

相关文章:

linux - 使用linux脚本发送电子邮件

linux - 如何将图像转换为低宽度 200

Java运行cURL并返回网站页面结果

jquery - Rails - 嵌套表单 - 随机化用户发布的所有单个字段

ruby - OS X 优胜美地 : Impossible to install cocoapods

c++ - 如何使用 Ruby 的 Enumerable .map 方法做一些类似于 C++ 中的 map 的事情

linux - 如何在 t1.micro 实例上更新 AWS RHEL 6.4 AMI 上的 curl

ruby - Selenium 滚动元素进入(中心) View

linux - 刷新陈旧的符号链接(symbolic link) linux

c - InfluxDB 返回错误的时间戳。我不知道为什么