Skip to content

Instantly share code, notes, and snippets.

@goerz
Created January 16, 2022 18:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save goerz/3d8f8a9257b431a4c8bd6a6d95722943 to your computer and use it in GitHub Desktop.
Save goerz/3d8f8a9257b431a4c8bd6a6d95722943 to your computer and use it in GitHub Desktop.
Find a string in a deeply nested Julia data structure
function find_string(obj, name::String, string::String)
for _name in propertynames(obj)
found = find_string(getproperty(obj, _name), name * "." * String(_name), string)
if !isnothing(found)
return found
end
end
end
function find_string(obj::String, name::String, string::String)
if occursin(string, obj)
return name
end
return nothing
end
function find_string(obj::AbstractVector, name::String, string::String)
for i in eachindex(obj)
found = find_string(obj[i], name * "[$i]", string)
if !isnothing(found)
return found
end
end
return nothing
end
function find_string(obj::AbstractDict, name::String, string::String)
for k in keys(obj)
found = find_string(obj[k], name * "[$(repr(k))]", string)
if !isnothing(found)
return found
end
end
return nothing
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment