0

I would like to convert a hash: {"key1"=>"value1", "key2"=>"value2"} into a string which looks like this: '[{"key1" : "value1","key2" : "value2"}]'

Background: I'm making an API call from my rails Controller. The curl equivalent of this request is curl -X POST -H 'Content-Type: application/json' -i 'valid_uri' --data '[{"key1" : "value1","key2" : "value2"}]'

So, to convert this in ruby, I tried the following:

require 'net/http'
require 'uri'
require 'json'

uri = URI.parse(VALID_URI)
header = {'Content-Type' => 'application/json'}
data = {"key1"=>"value1", "key2"=>"value2"}
http = Net::HTTP.new(uri.host, uri.port)
request = Net::HTTP::Post.new(uri.request_uri, header)
request.body = Array.wrap(data1.to_s.gsub('=>',':')).to_s
response = http.request(request)

However, the format of request.body doesn't match the format of data in curl request which results in Net::HTTPBadRequest 400 Bad Request

Can someone please explain how can I achieve this? TIA

Manitude
  • 100
  • 7

1 Answers1

1

just use the json module:

require "json"
h=[{"key1"=>"value1", "key2"=>"value2"}]
string=h.to_json # => [{"key1":"value1","key2":"value2"}]
Oliver Gaida
  • 1,722
  • 7
  • 14
  • Yes, it worked. I was under the impression that to_json works only with Hash. Thanks! – Manitude Jun 13 '19 at 20:23
  • You can convert any data-structur to json, arrays of arrays of hashes with arrays inside... By the way - do you know jq https://stedolan.github.io/jq/ . its to work with json data on commandline. – Oliver Gaida Jun 14 '19 at 06:26