convert String to Array reading from a file in julia

Viewed 158

I'm reading from a file that is structured like this

["EXPRESS", "VOLVO", "TESLA", "BYB"]

When I read it in Julia I get a string like this

"[\"FARMACIA\", \"SUPERMERCADO\"]"

I was wondering if there is a way to map that string to an array of strings like this

["FARMACIA", "SUPERMERCADO"]

Pls help , Thanks you

2 Answers

Use a JSON parser for that.

julia> mystr = """["EXPRESS", "VOLVO", "TESLA", "BYB"]"""
"[\"EXPRESS\", \"VOLVO\", \"TESLA\", \"BYB\"]"

julia> using JSON3

julia> JSON3.read(mystr)
4-element JSON3.Array{String,Base.CodeUnits{UInt8,String},Array{UInt64,1}}:
 "EXPRESS"
 "VOLVO"
 "TESLA"
 "BYB"

Note that Julia avoids unnecessary materializing data and memory copying and hence the "strange" type. You can however always run collect on the result:

julia> collect(JSON3.read(mystr))
4-element Array{String,1}:
 "EXPRESS"
 "VOLVO"
 "TESLA"
 "BYB"

Since you know the structure of the result, you can parse data straightforwardly

julia> mystr = """["EXPRESS", "VOLVO", "TESLA", "BYB"]"""
"[\"EXPRESS\", \"VOLVO\", \"TESLA\", \"BYB\"]"

julia> using JSON3

julia> JSON3.read(mystr, Vector{String})
4-element Vector{String}:
 "EXPRESS"
 "VOLVO"
 "TESLA"
 "BYB"

It's more efficient, since in this case JSON3 will not generate intermediate objects.

Related