不同的JSON响应 - {"count":"123"} vs {"count"=>"123"}

pab*_*808 1 php ruby json

我有一些PHP代码查询MySQL数据库的计数.

通过浏览器查询时,我得到以下输出:

{"count":"123"}
Run Code Online (Sandbox Code Playgroud)

我还有一个Ruby脚本,它通过Net :: HTTP执行相同的PHP脚本,但输出不同:

{"count"=>"123"}
Run Code Online (Sandbox Code Playgroud)

为什么是这样?

//The URL
uri = URI.parse("http://lab/count.php")
http = Net::HTTP.new(uri.host, uri.port)
//Request URL
request = Net::HTTP::Get.new(uri.request_uri)
//Basic authentication
request.basic_auth("user1", "secret")
response = http.request(request)
//Response
response = JSON.parse(response.body)
puts results
//Value 'count'
count = JSON.parse(response.body)[0]
puts count
Run Code Online (Sandbox Code Playgroud)

谢谢.

fal*_*tru 6

{"count"=>"123"} 不是JSON响应.

它是Hash表的ruby字面值.

我想你看到了解析JSON的结果:

>> require 'json'
>> JSON.parse('{"count":"123"}') # => {"count"=>"123"}
>> puts JSON.dump({"count"=>"123"}) # prints => {"count":"123"}
Run Code Online (Sandbox Code Playgroud)

更新评论回复

123打印.

uri = URI.parse("http://lab/count.php")
http = Net::HTTP.new(uri.host, uri.port)
request = Net::HTTP::Get.new(uri.request_uri)
request.basic_auth("user1", "secret")
response = http.request(request)
response = JSON.parse(response.body)
puts response['count']
Run Code Online (Sandbox Code Playgroud)