在Ruby中将HTTP响应转换为JSON

时间:2015-07-11 23:05:25

标签: ruby json

我正在做GET请求并收到此回复:

"oauth_token=USYS96A708CACBDA9C74322DAB41A53CA_idses-int02.a.fsglobal.net&oauth_token_secret=09c8b05b874fac29b4e542c388cb3f&oauth_callback_confirmed=true"

如何在Ruby中将其转换为JSON?

1 个答案:

答案 0 :(得分:6)

第1步:解析GET响应:

require 'cgi'

CGI::parse(MYSTRING)

返回:{"param1"=>["value1"], "param2"=>["value2"], "param3"=>["value3"]}

第2步。Convert to JSON

require 'json'

myObject.to_json

或者,请查看以下代码段:

https://gist.github.com/timsavery/1657351

require "rubygems"
require "json"
require "net/http"
require "uri"

uri = URI.parse("http://api.sejmometr.pl/posiedzenia/BZfWZ/projekty")

http = Net::HTTP.new(uri.host, uri.port)
request = Net::HTTP::Get.new(uri.request_uri)

response = http.request(request)

if response.code == "200"
  result = JSON.parse(response.body)

  result.each do |doc|
    puts doc["id"] #reference properties like this
    puts doc # this is the result in object form
    puts ""
    puts ""
  end
else
  puts "ERROR!!!"
end