2

I have the following which works in bash:

curl -d "{ \"auth_token\": \"secret\", \"current\":"${COUNT}"}" http://lab:3030/widgets/connections

But if I tried this in Ruby is fails:

`curl -d "{\"auth_token\":\"secret\",\"current\":"#{count}"}" http://lab:3030/widgets/connections`

And get this error message:

JSON::ParserError - 746: unexpected token at '{auth_token:secret,current:4}':

The output of from Ruby appears to look correct on screen but trigger the JSON parser error. What else can I check for?

I was thinking about using a gem like curb-fu but could not figure out how to construct it to look the same as the bash one above.

Thanks.

2 Answers 2

4

You can use stdlib's json to convert the hash:

require 'json'

{foo: "bar"}.to_json
#=> "{\"foo\":\"bar\"}"

and shellwords to build the command:

require 'shellwords'

['curl', '-d', '{"foo":"bar"}', 'http://example.com/'].shelljoin
#=> "curl -d \\{\\\"foo\\\":\\\"bar\\\"\\} http://example.com/"

Complete example:

require 'json'
require 'shellwords'

data = {auth_token: secret, current: count}
`#{['curl', '-d', data.to_json, 'http://lab:3030/widgets/connections'].shelljoin}`
Sign up to request clarification or add additional context in comments.

1 Comment

I think it's better to include the require 'shellwords' in sample code.
2

It looks like you have an escaping issue: The quotes are not being escaped properly in the Ruby version. Try this:

`curl -d "{\\"auth_token\\":\\"secret\\",\\"current\\":"#{count}"}" http://lab:3030/widgets/connections`

This is because both Ruby and the shell escape with the backslash, so escaping happens twice. By adding the extra backslash, the Ruby version is escaped to \" instead of just " and then shell can escape the quote for you.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.