-
-
Save silgon/0ba43e00e0749cdf4f8d244e67cd9d6a to your computer and use it in GitHub Desktop.
| import JSON | |
| ################### | |
| ### Write data #### | |
| ################### | |
| # dictionary to write | |
| dict1 = Dict("param1" => 1, "param2" => 2, | |
| "dict" => Dict("d1"=>1.,"d2"=>1.,"d3"=>1.)) | |
| # pass data as a json string (how it shall be displayed in a file) | |
| stringdata = JSON.json(dict1) | |
| # write the file with the stringdata variable information | |
| open("write_read.json", "w") do f | |
| write(f, stringdata) | |
| end | |
| ################### | |
| ### Read data ##### | |
| ################### | |
| # create variable to write the information | |
| dict2 = Dict() | |
| open("write_read.json", "r") do f | |
| global dict2 | |
| dicttxt = readall(f) # file information to string | |
| dict2=JSON.parse(dicttxt) # parse and transform data | |
| end | |
| # print both dictionaries | |
| println(dict1) | |
| println(dict2) |
Very helpfull. Thanks for sharing.
How to get the value, because is showing in my console: Dict{Any,Any}()
I think the readall(f) call was supposed to be JSON.readall
# create variable to write the information
dict2 = Dict()
open("write_read.json", "r") do f
global dict2
dicttxt = read(f,String) # file information to string
dict2=JSON.parse(dicttxt) # parse and transform data
endand
# create variable to write the information
dict2 = Dict()
open("write_read.json", "r") do f
global dict2
dict2=JSON.parse(f) # parse and transform data
endworked!
It seems the name of text-read function has been changed at least twice: readall -> readstring -> read
JuliaLang/julia#14660
JuliaLang/julia#22864
Julia v1.5 update: for reading data I use
stringdata=join(readlines("/path/data.json"))
dict=JSON.parse(stringdata)
Using Julia v1.5 and the Pipe module you can read the json file to a dict in one line:
dict = @pipe "write_read.json" |> open |> read |> String |> JSON.parse
Using Julia v1.6, I was able to read the json file in a very simple way.
dict = "write_read.json" |> open |> JSON.parse
OR
dict = JSON.parse(open("write_read.json"))
I think JSON.parsefile("filename.json") is the right way to do this now?
The 'readall' call fails with 'ERROR: UndefVarError: readall not defined'. If 'readall' is replaced by 'readstring', it works fine.