Search code examples
rubyruby-on-rails-5net-http

Convert Hash to specific string format in ruby


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


Solution

  • just use the json module:

    require "json"
    h=[{"key1"=>"value1", "key2"=>"value2"}]
    string=h.to_json # => [{"key1":"value1","key2":"value2"}]