Add @this modifier

This modifier returns the current element as-is and can be used
to retrieve the JSON document itself. It is equivalent to the `#/` JSON Pointer.

Closes #149
This commit is contained in:
aeneasr 2020-01-13 11:51:52 +01:00
parent 5c2e4b3824
commit 8e8823353c
No known key found for this signature in database
GPG Key ID: 998E76A674F4A689
3 changed files with 14 additions and 1 deletions

View File

@ -186,6 +186,7 @@ There are currently three built-in modifiers:
- `@reverse`: Reverse an array or the members of an object. - `@reverse`: Reverse an array or the members of an object.
- `@ugly`: Remove all whitespace from JSON. - `@ugly`: Remove all whitespace from JSON.
- `@pretty`: Make the JSON more human readable. - `@pretty`: Make the JSON more human readable.
- `@this`: Returns the current element. Can be used to retrieve the root element.
#### Modifier arguments #### Modifier arguments

View File

@ -1989,7 +1989,7 @@ func runeit(json string) rune {
} }
// unescape unescapes a string // unescape unescapes a string
func unescape(json string) string { //, error) { func unescape(json string) string { // , error) {
var str = make([]byte, 0, len(json)) var str = make([]byte, 0, len(json))
for i := 0; i < len(json); i++ { for i := 0; i < len(json); i++ {
switch { switch {
@ -2746,6 +2746,7 @@ var modifiers = map[string]func(json, arg string) string{
"pretty": modPretty, "pretty": modPretty,
"ugly": modUgly, "ugly": modUgly,
"reverse": modReverse, "reverse": modReverse,
"this": modThis,
} }
// AddModifier binds a custom modifier command to the GJSON syntax. // 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))) 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. // @ugly modifier removes all whitespace.
func modUgly(json, arg string) string { func modUgly(json, arg string) string {
return bytesString(pretty.Ugly(stringBytes(json))) return bytesString(pretty.Ugly(stringBytes(json)))

View File

@ -1519,6 +1519,12 @@ func TestModifier(t *testing.T) {
if res != json { if res != json {
t.Fatalf("expected '%v', got '%v'", json, res) 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() res = Get(res, "@pretty|@reverse|arr|@reverse|2").String()
if res != "4" { if res != "4" {
t.Fatalf("expected '%v', got '%v'", "4", res) t.Fatalf("expected '%v', got '%v'", "4", res)