diff --git a/SYNTAX.md b/SYNTAX.md index a57a4d6..ed584de 100644 --- a/SYNTAX.md +++ b/SYNTAX.md @@ -186,6 +186,7 @@ There are currently three built-in modifiers: - `@reverse`: Reverse an array or the members of an object. - `@ugly`: Remove all whitespace from JSON. - `@pretty`: Make the JSON more human readable. +- `@this`: Returns the current element. Can be used to retrieve the root element. #### Modifier arguments diff --git a/gjson.go b/gjson.go index 8705ee2..203db3d 100644 --- a/gjson.go +++ b/gjson.go @@ -1989,7 +1989,7 @@ func runeit(json string) rune { } // unescape unescapes a string -func unescape(json string) string { //, error) { +func unescape(json string) string { // , error) { var str = make([]byte, 0, len(json)) for i := 0; i < len(json); i++ { switch { @@ -2746,6 +2746,7 @@ var modifiers = map[string]func(json, arg string) string{ "pretty": modPretty, "ugly": modUgly, "reverse": modReverse, + "this": modThis, } // AddModifier binds a custom modifier command to the GJSON syntax. @@ -2783,6 +2784,11 @@ func modPretty(json, arg string) string { return bytesString(pretty.Pretty(stringBytes(json))) } +// @this returns the current element. Can be used to retrieve the root element. +func modThis(json, arg string) string { + return json +} + // @ugly modifier removes all whitespace. func modUgly(json, arg string) string { return bytesString(pretty.Ugly(stringBytes(json))) diff --git a/gjson_test.go b/gjson_test.go index 5f2711d..04031ec 100644 --- a/gjson_test.go +++ b/gjson_test.go @@ -1519,6 +1519,12 @@ func TestModifier(t *testing.T) { if res != json { t.Fatalf("expected '%v', got '%v'", json, res) } + if res := Get(res, "@this").String(); res != json { + t.Fatalf("expected '%v', got '%v'", json, res) + } + if res := Get(res, "other.@this").String(); res != `{"hello":"world"}` { + t.Fatalf("expected '%v', got '%v'", json, res) + } res = Get(res, "@pretty|@reverse|arr|@reverse|2").String() if res != "4" { t.Fatalf("expected '%v', got '%v'", "4", res)