Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/14.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端点处的文件替换目录中的整个文件_Ruby_Json - Fatal编程技术网

用ruby中URL端点处的文件替换目录中的整个文件

用ruby中URL端点处的文件替换目录中的整个文件,ruby,json,Ruby,Json,假设我的工作目录中有以下文件: path/to/my/file/fileToBeReplaced.json 我在以下URL端点处有一个文件: mywebsite.com/fileToCopy.json 我想在URL端点(fileToCopy.json)获取该文件,并在那里获取内容,以覆盖我的工作目录(filetobereplace.json)中的文件。将文件写入工作目录时,保留json格式也很重要。如何在Ruby脚本中实现这一点 您可以这样做: require 'net/http' Fil

假设我的工作目录中有以下文件:

path/to/my/file/fileToBeReplaced.json
我在以下URL端点处有一个文件:

mywebsite.com/fileToCopy.json

我想在URL端点(fileToCopy.json)获取该文件,并在那里获取内容,以覆盖我的工作目录(filetobereplace.json)中的文件。将文件写入工作目录时,保留json格式也很重要。如何在Ruby脚本中实现这一点

您可以这样做:

require 'net/http'

File.open("path/to/my/file/fileToBeReplaced.json", "w") do |f|
   f.write Net::HTTP.get('mywebsite.com', '/fileToCopy.json')
end
require 'net/http'
require 'json'

File.open("path/to/my/file/fileToBeReplaced.json", "w") do |f|
   json_str = Net::HTTP.get('mywebsite.com', '/fileToCopy.json')
   json_hash = JSON.parse(json_str)
   f.puts JSON.pretty_generate(json_hash)
end
如果URL中的JSON格式不正确,则可以尝试以下方法:

require 'net/http'

File.open("path/to/my/file/fileToBeReplaced.json", "w") do |f|
   f.write Net::HTTP.get('mywebsite.com', '/fileToCopy.json')
end
require 'net/http'
require 'json'

File.open("path/to/my/file/fileToBeReplaced.json", "w") do |f|
   json_str = Net::HTTP.get('mywebsite.com', '/fileToCopy.json')
   json_hash = JSON.parse(json_str)
   f.puts JSON.pretty_generate(json_hash)
end

可能会重复此操作,但不会保留json格式。我试着在f.write行的末尾添加“to_json”,但它只是在空白处插入/。嗯。。。我得到了保留格式的文件。您的URL是否返回带格式的JSON?更新了我的答案,显示了
JSON#pretty_generate
的用法,看起来我使用的是Ruby 1.8。哈希函数在1.8中未定义,但在1.9中是插入顺序,因此升级修复了此问题。