Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/multithreading/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用Ruby从URL获取JSON,抛出TypeError和';无法打开TCP连接';_Json_Ruby_Terminal - Fatal编程技术网

使用Ruby从URL获取JSON,抛出TypeError和';无法打开TCP连接';

使用Ruby从URL获取JSON,抛出TypeError和';无法打开TCP连接';,json,ruby,terminal,Json,Ruby,Terminal,背景 我有一个Ruby终端应用程序,它生成一个URL,然后从该URL获取JSON 手动跟随链接()显示一个JSON对象,但程序抛出两个错误 (没有将数组隐式转换为字符串)(TypeError) 无法打开到[{“kind”=>“books#volume”,“id”=>“2sSMCwAAQBAJ”,“etag”=>“vAZ9LJGLnng”,“selfLink”=>“,“volumeInfo”=>{“title”=>“哈利波特与诅咒的孩子-第一部分和第二部分(特别排练版)”,“authors”=>[

背景

我有一个Ruby终端应用程序,它生成一个URL,然后从该URL获取JSON

手动跟随链接()显示一个JSON对象,但程序抛出两个错误

  • (没有将数组隐式转换为字符串)(TypeError)
  • 无法打开到[{“kind”=>“books#volume”,“id”=>“2sSMCwAAQBAJ”,“etag”=>“vAZ9LJGLnng”,“selfLink”=>“,“volumeInfo”=>{“title”=>“哈利波特与诅咒的孩子-第一部分和第二部分(特别排练版)”,“authors”=>[“J.K.罗琳”,“约翰·蒂凡尼”,“杰克·索恩”…(很长)
  • 我很困惑,因为它说它无法打开连接,但数据在那里,尽管它的格式不同

    我的代码

    有关守则如下

        response = Net::HTTP.get_response(link,"")
        puts response.body -- error is thrown on line above, so this is commented out
    
    注意:本例中的“链接”是我给出的第一个链接

    问题


    如何更正给定的错误,以便我的应用程序获得JSON对象?

    要获得响应,请尝试以下操作:

    require 'json'
    require 'net/http'
    
    url = 'https://www.googleapis.com/books/v1/volumes?q=Harry+Potter'
    
    # get JSON as String
    json = Net::HTTP.get(URI.parse(url))
    
    # get Hash from JSON
    hash = JSON.parse(json)
    
    问题在于URI解析

    您还可以通过以下方式执行此操作:

    Net::HTTP.get_response(URI.parse(url)).body
    

    我想已经完成了。这只是一个没有解析结果的问题吗?是的。解析是个问题。我在答案中添加了信息。如果它对您有帮助,您可以检查它。