0

I have Dict and all keys in that Dict have their own Types with the same name, so I need to get the Key but not as String, as Type.

toStruct function get two parameters, the first is the Type (in my case is the same as the Key) and the second is the Dict

julia> jsonDict Dict{String, Any} with 2 entries: "TypeExample1" => Dict{String, Any}("attr" => 5) "TypeExample2" => Dict{String, Any}("attr" => 10) struct TypeExample1 attr end struct TypeExample2 attr end for (key, value) in jsonDict ToStruct.tostruct( Key, key) end 

the code above would not work obviously cause Key is a String the output should be 2 structs (TypeExample1,TypeExample2) with the assigned values

PS: it would work like this:

 ToStruct.tostruct( TypeExample1, jsonDict["TypeExample1"]) 

but I need to automate this process

1
  • Could you please add and example of a dict pair?, and what the output should look like Commented Sep 16, 2021 at 14:16

1 Answer 1

1

The quick and dirty way to achieve this is to use eval.

julia> eval(Symbol("Int")) Int64 

This is of course not limited to types but works for any variable and should not be used on untrusted text.

By using the eval of a specific module (Module.eval) you can evaluate the symbol in that module.

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you, I have read about eval() but I do not know why it is not recommended, is there any performance problems comes with it?
The primary concern is usually security, eval with a dynamic argument opens up a big attack surface even when used in a fairly controlled way like here. Performance is also an issue with eval. In this particular case mostly because the type can't be known. Do you really need the full flexibility of any type or could you create a list of allowed types?
aha okay, no it could be listed of 5 allowed types

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.