Skip to content

Commit

Permalink
Add tostr and fromstr modifiers
Browse files Browse the repository at this point in the history
For wrapping and unwrapping json strings
  • Loading branch information
tidwall committed Jan 13, 2022
1 parent ba95ef8 commit 38071ea
Show file tree
Hide file tree
Showing 4 changed files with 28 additions and 0 deletions.
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -204,6 +204,8 @@ There are currently the following built-in modifiers:
- `@join`: Joins multiple objects into a single object.
- `@keys`: Returns an array of keys for an object.
- `@values`: Returns an array of values for an object.
- `@tostr`: Converts json to a string. Wraps a json string.
- `@fromstr`: Converts a string from json. Unwraps a json string.

### Modifier arguments

Expand Down
2 changes: 2 additions & 0 deletions SYNTAX.md
Original file line number Diff line number Diff line change
Expand Up @@ -238,6 +238,8 @@ There are currently the following built-in modifiers:
- `@join`: Joins multiple objects into a single object.
- `@keys`: Returns an array of keys for an object.
- `@values`: Returns an array of values for an object.
- `@tostr`: Converts json to a string. Wraps a json string.
- `@fromstr`: Converts a string from json. Unwraps a json string.

#### Modifier arguments

Expand Down
18 changes: 18 additions & 0 deletions gjson.go
Original file line number Diff line number Diff line change
Expand Up @@ -2669,6 +2669,8 @@ var modifiers = map[string]func(json, arg string) string{
"valid": modValid,
"keys": modKeys,
"values": modValues,
"tostr": modToStr,
"fromstr": modFromStr,
}

// AddModifier binds a custom modifier command to the GJSON syntax.
Expand Down Expand Up @@ -2954,6 +2956,22 @@ func modValid(json, arg string) string {
return json
}

// @fromstr converts a string to json
// "{\"id\":1023,\"name\":\"alert\"}" -> {"id":1023,"name":"alert"}
func modFromStr(json, arg string) string {
if !Valid(json) {
return ""
}
return Parse(json).String()
}

// @tostr converts a string to json
// {"id":1023,"name":"alert"} -> "{\"id\":1023,\"name\":\"alert\"}"
func modToStr(str, arg string) string {
data, _ := json.Marshal(str)
return string(data)
}

// stringHeader instead of reflect.StringHeader
type stringHeader struct {
data unsafe.Pointer
Expand Down
6 changes: 6 additions & 0 deletions gjson_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2461,3 +2461,9 @@ func TestArrayKeys(t *testing.T) {
})
assert(t, i == N)
}

func TestToFromStr(t *testing.T) {
json := `{"Message":"{\"Records\":[{\"eventVersion\":\"2.1\"}]"}`
res := Get(json, "Message.@fromstr.Records.#.eventVersion.@tostr").Raw
assert(t, res == `["\"2.1\""]`)
}

0 comments on commit 38071ea

Please sign in to comment.