这是python代码:
with open('config.json') as json_data_file:
configuration = json.load(json_data_file)
access_token=configuration["canvas"]["access_token"]
baseUrl="https://"+configuration["canvas"]["host"]+"/api/v1/courses/"
header = {'Authorization' : 'Bearer ' + access_token}
我正在尝试用ruby编写一些代码,其功能与上述python代码完全相同。这是我的写法:
File.open("config.json") {|json_data_file|
configuration = json.load(json_data_file)
access_token=configuration["canvas"]["access_token"]
baseUrl="https://"+configuration["canvas"]["host"]+"/api/v1/courses/"
}
header = {'Authorization': 'Bearer ' + access_token}
这是正确的方法吗?
答案 0 :(得分:2)
比这简单。您使用IO#read以字符串形式返回文件内容,然后使用JSON.parse将JSON转换为Ruby结构。
说这是您的config.json
文件:
{
"canvas": {
"access_token": "i like pie",
"host": "ilikepie.com"
}
}
并以Ruby代码访问config.json
中的信息:
# You need to require JSON
require 'json'
config_file = File.read('config.json')
config_hash = JSON.parse(config_file)
# Now you can access everything from `config_hash`
access_token = config_hash['canvas']['access_token'] # => 'i like pie'
host = config_hash['canvas']['host'] # => 'ilikepie.com'
您最终的Ruby代码应如下所示:
require 'json'
config = JSON.parse(File.read('config.json'))
access_token = config['canvas']['access_token']
host = config['canvas']['host']
# Use snake case in Ruby scripts. Also, use string interpolation, it's much clearer.
base_url = "https://#{host}/api/v1/courses/" # => 'https://ilikepie.com/api/v1/courses/'