From 1234215037d806ffbb0b85c48bc4f19e3ad0dbda Mon Sep 17 00:00:00 2001 From: Mike Farah Date: Sun, 27 Sep 2015 13:40:09 +1000 Subject: [PATCH] Can handle arrays --- README.md | 17 +++++++++++++++++ sample.yaml | 5 +++++ yaml.go | 30 +++++++++++++++++++++++++++--- 3 files changed, 49 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index d0748862..8e56411d 100644 --- a/README.md +++ b/README.md @@ -13,3 +13,20 @@ E.g.: yaml sample.yaml b.c ``` will output the value of '2'. + +Arrays: +Just use the index to access a specific element: +e.g.: given +``` +b: + e: + - name: fred + value: 3 + - name: sam + value: 4 +``` +then +``` +yaml sample.yaml b.e.1.name +``` +will output 'sam' diff --git a/sample.yaml b/sample.yaml index 88d6c32d..2024cbf4 100644 --- a/sample.yaml +++ b/sample.yaml @@ -2,3 +2,8 @@ a: Easy! as one two three b: c: 2 d: [3, 4] + e: + - name: fred + value: 3 + - name: sam + value: 4 diff --git a/yaml.go b/yaml.go index 18ed68ff..271b39c3 100644 --- a/yaml.go +++ b/yaml.go @@ -8,6 +8,7 @@ import ( "os" "github.com/codegangsta/cli" "strings" + "strconv" ) func main() { @@ -33,7 +34,7 @@ func read_property(c *cli.Context) { var path = c.Args()[1] var paths = strings.Split(path, ".") - fmt.Println(read(parsed_data, paths[0], paths[1:len(paths)])) + fmt.Println(read_map(parsed_data, paths[0], paths[1:len(paths)])) } func read_yaml(c *cli.Context, parsed_data *map[interface{}]interface{}) { @@ -61,11 +62,34 @@ func read_file(filename string) []byte { return raw_data } -func read(context map[interface{}]interface{}, head string, tail []string) interface{} { +func read_map(context map[interface{}]interface{}, head string, tail []string) interface{} { value := context[head] if (len(tail) > 0) { - return read(value.(map[interface{}]interface{}), tail[0], tail[1:len(tail)]) + return recurse(value, tail[0], tail[1:len(tail)]) } else { return value } } + +func recurse(value interface{}, head string, tail []string) interface{} { + switch value.(type) { + case []interface {}: + index, err := strconv.ParseInt(head, 10, 64) + if err != nil { + log.Fatalf("Error accessing array: %v", err) + } + return read_array(value.([]interface {}), index, tail) + default: + return read_map(value.(map[interface{}]interface{}), head, tail) + } +} + +func read_array(array []interface {}, head int64, tail[]string) interface{} { + value := array[head] + if (len(tail) > 0) { + return recurse(value, tail[0], tail[1:len(tail)]) + } else { + return value + } +} +