Json 朱莉娅:将文件读入本地范围外的字符串
这是我第一次在Julia上写文章,我对变量作用域的工作原理感到困惑,尽管我在文档中读过 我编写这个简单的脚本来读取JSON文件的内容并将其解析为Dict:Json 朱莉娅:将文件读入本地范围外的字符串,json,julia,Json,Julia,这是我第一次在Julia上写文章,我对变量作用域的工作原理感到困惑,尽管我在文档中读过 我编写这个简单的脚本来读取JSON文件的内容并将其解析为Dict: import JSON using ArgParse s = ArgParseSettings() @add_arg_table! s begin "filename" help = "a positional argument" arg_type = String required
import JSON
using ArgParse
s = ArgParseSettings()
@add_arg_table! s begin
"filename"
help = "a positional argument"
arg_type = String
required = true
end
function main(args)
jsontxt = ""
open(args["filename"], "r") do f
global jsontxt = read(f, String) # file information to string
println(jsontxt)
end
model_params = JSON.parse(jsontxt) # parse and transform data
println(model_params)
end
parsed_args = parse_args(ARGS, s)
main(parsed_args)
因此,当我将jsontxt
变量传递给JSON.parse时,我希望该变量包含read(f,String)
的结果。然而,当我调用JSON.parse
时,jsontxt
似乎是空的,就像在main
函数范围中一样。从阅读类似(或者我认为是这样)的文件阅读示例中,我的期望是,如果我将jsontxt
内容定义为global
变量,我会更改它,但这似乎不会发生
我误解了什么?如何纠正
运行脚本的JSON示例:
{
"glossary": {
"title": "example glossary",
"GlossDiv": {
"title": "S",
"GlossList": {
"GlossEntry": {
"ID": "SGML",
"SortAs": "SGML",
"GlossTerm": "Standard Generalized Markup Language",
"Acronym": "SGML",
"Abbrev": "ISO 8879:1986",
"GlossDef": {
"para": "A meta-markup language, used to create markup languages such as DocBook.",
"GlossSeeAlso": ["GML", "XML"]
},
"GlossSee": "markup"
}
}
}
}
}
只要去掉global
注释,代码就可以正常工作jsontxt
是在本地范围内定义的,因此global jsontxt
不会引用它
尝试一下下面的代码以了解发生了什么
import JSON
using ArgParse
s = ArgParseSettings()
@add_arg_table! s begin
"filename"
help = "a positional argument"
arg_type = String
required = true
end
jsontxt = ""
function main(args)
jsontxt = "{}" # add a `global` here and your code works fine
open(args["filename"], "r") do f
global jsontxt = read(f, String) # remove the `global` here and your code works fine
println("inner local scope:")
println(jsontxt)
end
model_params = JSON.parse(jsontxt) # parse and transform data
println("outer local scope:")
println(model_params)
end
parsed_args = parse_args(ARGS, s)
main(parsed_args)
println("global scope:")
println(jsontxt)
它将输出如下内容
$ julia test.jl test.json
inner local scope:
{
"foo": "bar"
}
outer local scope:
Dict{String,Any}()
global scope:
{
"foo": "bar"
}