Skip to content

Commit

Permalink
Add @this modifier
Browse files Browse the repository at this point in the history
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
  • Loading branch information
aeneasr committed Jan 20, 2020
1 parent 5c2e4b3 commit 8e88233
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 1 deletion.
1 change: 1 addition & 0 deletions SYNTAX.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
8 changes: 7 additions & 1 deletion gjson.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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)))
Expand Down
6 changes: 6 additions & 0 deletions gjson_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down

0 comments on commit 8e88233

Please sign in to comment.