forked from mirror/gjson
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:
parent
5c2e4b3824
commit
8e8823353c
|
@ -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
|
||||
|
||||
|
|
8
gjson.go
8
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)))
|
||||
|
|
|
@ -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)
|
||||
|
|
Loading…
Reference in New Issue