将哈希转换为Ruby中的特定字符串格式

时间:2019-06-13 20:10:12

标签: ruby ruby-on-rails-5 net-http

我想将散列{"key1"=>"value1", "key2"=>"value2"}转换为如下所示的字符串:'[{"key1" : "value1","key2" : "value2"}]'

背景:我正在从Rails Controller进行API调用。 此请求的curl等效为curl -X POST -H 'Content-Type: application/json' -i 'valid_uri' --data '[{"key1" : "value1","key2" : "value2"}]'

因此,为了将其转换为红宝石,我尝试了以下操作:

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)

但是,request.body的格式与curl请求中的数据格式不匹配,导致 Net :: HTTPBadRequest 400 Bad Request

有人可以解释一下我该如何实现吗? TIA

1 个答案:

答案 0 :(得分:1)

只需使用json模块:

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