Parsing Array of Strings to Object in Julia

Viewed 176

I have the following string

l = "['name1', 'name2', 'name3']"

Now, I'd like to turn this into a proper array of strings, such as:

["name1","name2","name3"]

I know that one can use Meta.parse in Julia, to turn an expression into a Julia object. The following code works:

Meta.parse("['a','b','c']")

But when each string has more than one character, Julia gives the following error message:

Base.Meta.ParseError("character literal contains multiple characters")

Any idea on how to solve this problem?

2 Answers

You could use replace to change the ''s (which are used for chars) into "'s (which are used for strings) in the string before parsing it:

Meta.parse(replace(l, "'" => '"'))

Use JSON3 package:

julia> JSON3.read(replace("['name1', 'name2', 'name3']", "'"=>"\""))
3-element JSON3.Array{String,Base.CodeUnits{UInt8,String},Array{UInt64,1}}:
 "name1"
 "name2"
 "name3"
Related