Add tostr and fromstr modifiers

For wrapping and unwrapping json strings
This commit is contained in:
tidwall 2022-01-13 09:15:39 -07:00
parent ba95ef80b5
commit 38071ea7f2
4 changed files with 28 additions and 0 deletions

View File

@ -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

View File

@ -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

View File

@ -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.
@ -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

View File

@ -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\""]`)
}