Similar to this question, but even more runtime-ey.
Is there a way to automatically generate lenses, or any other mechanism, for accessing fields by name at runtime?
I'm looking for something similar to field
from generic-lens
, except taking the field name as a runtime argument instead of a type-leve parameter (and returning a Maybe
).
I'm comfortable enough writing this myself, but I think it probably already exists.
Example
data Foo = Foo { bar :: Bar }
data Bar = ...
Deriving Generic
, you can use generic-lens
to get the handy field @"bar"
lens - but is there any way to automatically generate/derive a fieldAtRuntime "bar"
which behaves the same (or a similar) way?
Motivation
I want to navigate some custom data structures using JSON paths. It doesn't really matter to me that the JSON might not match up exactly with the record fields, but I do want to not have to serialize, traverse, and de-serialize.