convert Julia expression to array?

Viewed 94

im getting a list that was saved as a string, and trying to parse it to use. I can use Meta.parse, to turn the string into an expression :

li = db.list
print(typeof(d[1]),d[1])
>> String
   ["apple", "banana", "coconut"]

parsed_li = Meta.parse(d[1])
print(typeof(parsed_li), parsed_li)
>> Expr
   ["apple", "banana", "coconut"]

but it doesnt seem like i can use it like a normal list ; for example, with a normal list i could access an element by its index, but i cannot access the index of the Expr object :

normal_li = ["apple", "banana", "coconut"]
print(normal_li[1])
>> apple

print(parsed_li[1])
>>
MethodError: no method matching getindex(::Expr, ::Int64)

Stacktrace:
 [1] top-level scope at In[214]:8

i've been tinkering , not sure what I'm missing here!

3 Answers

Relying on Meta.parse() to parse your input data is both inefficient and unsafe (malicious code can be always inserted in the input data and you might be doing eval on it etc.). You rather instead use tools that are designed just for it. In your case just note that this data can be considered as a valid JSON format and can be read as follows:


julia> str = """["apple", "banana", "coconut"]"""
"[\"apple\", \"banana\", \"coconut\"]"

julia> using JSON3

julia> JSON3.read(str)
3-element JSON3.Array{String, Base.CodeUnits{UInt8, String}, Vector{UInt64}}:
 "apple"
 "banana"
 "coconut"

julia> collect(JSON3.read(str))
3-element Vector{String}:
 "apple"
 "banana"
 "coconut"

If you trust the input data (normally you never should) you can do it the unsafe way:

julia> eval(Meta.parse(str))
3-element Vector{String}:
 "apple"
 "banana"
 "coconut"

If you want to extract the information without eval, it could be done using args field of the Expr object - however the way it is handled will each time strongly depend on data structure:

julia> Meta.parse(str).args
3-element Vector{Any}:
 "apple"
 "banana"
 "coconut"

It's aways down in the docs page: evaled_li = eval(parsed_li) will be a Vector of String.

Expr is not a list-like data structure.

Quoted from the doc

Expr

A type representing compound expressions in parsed julia code (ASTs). Each expression consists of a head Symbol identifying which kind of expression it is (e.g. a call, for loop, conditional statement, etc.), and subexpressions (e.g. the arguments of a call). The subexpressions are stored in a Vector{Any} field called args.

You can still access those elements through the args field though if you want.

Related