4

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 2

2

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"
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.