JSON3 indexing nested object by string path

Given:

using JSON3

json_string = """
{
    "name": "rocket1",
    "observations": [
        {
            "speed": "100",
            "acceleration": "1"
        },
        {
            "speed": "200",
            "acceleration": "2"
        }
    ]
}
"""

json = JSON3.read(json_string)

json leaves then can be indexed with the following paths:

[:name]
[:observations][1][:speed]
[:observations][1][:acceleration]
[:observations][2][:speed]
[:observations][2][:acceleration]

for example:


json[:observations][2][:speed] # returns "200"

How could it be indexed if the path was stored in a string? Like this:

path = "[:observations][2][:speed]"
json[path] # how? any clue?

Thank you

You’d have to do some parsing of the string. Wouldn’t it be easier to store a tuple of indices, e.g. (:observations, 2, :speed)?

1 Like

Nice! Yes, it is.


function get(json, path)
    result = json
    for node in path
        result = getindex(result, node)
    end
    result
end

path = (:observations, 2, :speed)
get(json, path)