Skip to content
/ selectr Public

Select values from objects/arrays with key-path notation.

License

Notifications You must be signed in to change notification settings

0xch4z/selectr

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

48 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

selectr GoDoc test

Select values from objects/arrays with key-path notation.

Key-path notation

Key-path notation is a simple format for describing how to traverse data structures. It's very similar to C languages, but with limitations. See the reference document for more information.

Usage

m := map[string]interface{}{
    "foo": map[string]interface{}{
        "bar": []interface{}{
            1,
            2,
            3,
        },
    },
}

sel, _ := selectr.Parse(".foo")
sel.Resolve(m) // => map[string]interface{}{"bar": []interface{}{1, 2, 3}}

sel, _ = selectr.Parse(".foo.bar")
sel.Resolve(m) // => []interface{}{1, 2, 3}

sel, _ = selectr.Parse(".foo.bar[1]")
sel.Resolve(m) // => 2

Use cases

  • Referencing a dynamic value in a JSON/YAML file:

    Consider you maintain a program that allows users to reference arbitrary values, and one strategy of resolving a value is referencing a symbol in a JSON file.

    # example.json
    {
        "accounts": [{
            "id": 123,
            "name": "main"
        }]
    }

    The end-user references example.json with the selectr .accounts[0].name.

    jsonBytes, _ := os.Open(fileName)
    
    var m map[string]interface{}
    json.Unmarshal(jsonBytes, &m)
    
    sel, _ := selectr.Parse(selectrString)
    val := sel.Resolve(m)

    The val is resolved to "main".

  • Import dynamic values from dynamic data files.