从 json 到 ruby 哈希?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9055096/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
from json to a ruby hash?
提问by beoliver
I can go one way using
我可以用一种方法
require 'json'
def saveUserLib(user_lib)
File.open("/Users/name/Documents/user_lib.json","w") do |f|
f.write($user_lib.to_json)
end
end
uname = gets.chomp
$user_lib["_uname"] = uname
saveUserLib($user_lib)
but how do i get it back again as my user_lib?
但是我如何将它作为我的 user_lib 重新找回?
回答by Phrogz
You want JSON.parseor JSON.load:
你想要JSON.parse或JSON.load:
def load_user_lib( filename )
JSON.parse( IO.read(filename) )
end
The key here is to use IO.readas a simple way to load the JSON string from disk, so that it can be parsed. Or, if you have UTF-8 data in your file:
这里的关键是IO.read作为一种从磁盘加载 JSON 字符串的简单方法,以便对其进行解析。或者,如果您的文件中有 UTF-8 数据:
my_object = JSON.parse( IO.read(filename, encoding:'utf-8') )
I've linked to the JSON documentation above, so you should go read that for more details. But in summary:
我已链接到上面的 JSON 文档,因此您应该阅读该文档以了解更多详细信息。但总而言之:
json = my_object.to_json— method on the specific object to create a JSON string.json = JSON.generate(my_object)—?create JSON string from object.JSON.dump(my_object, someIO)— create a JSON string and write to a file.my_object = JSON.parse(json)— create a Ruby object from a JSON string.my_object = JSON.load(someIO)— create a Ruby object from a file.
json = my_object.to_json— 在特定对象上创建 JSON 字符串的方法。json = JSON.generate(my_object)—? 从对象创建 JSON 字符串。JSON.dump(my_object, someIO)— 创建一个 JSON 字符串并写入文件。my_object = JSON.parse(json)— 从 JSON 字符串创建一个 Ruby 对象。my_object = JSON.load(someIO)— 从文件创建一个 Ruby 对象。
Alternatively:
或者:
def load_user_lib( filename )
File.open( filename, "r" ) do |f|
JSON.load( f )
end
end
Note: I have used a "snake_case" name for the method corresponding to your "camelCase" saveUserLibas this is the Ruby convention.
注意:我为与您的“camelCase”相对应的方法使用了“snake_case”名称,saveUserLib因为这是 Ruby 约定。
回答by alexkv
here is some example:
这是一些例子:
require 'json'
source_hash = {s: 12, f: 43}
json_string = JSON.generate source_hash
back_to_hash = JSON.parse json_string
回答by Chris Bunch
JSON.loadwill do the trick. Here's an example that goes both ways:
JSON.load会做的伎俩。这是一个双向的例子:
>> require 'json'
=> true
>> a = {"1" => "2"}
=> {"1"=>"2"}
>> b = JSON.dump(a)
=> "{\"1\":\"2\"}"
>> c = JSON.load(b)
=> {"1"=>"2"}

