Skip to content

Commit

Permalink
Possibility to extract parts of a json-message. (#271)
Browse files Browse the repository at this point in the history
* Possibility to extract parts of a json-message.

* Fix some small things based on review comments.

* Fix review comment

Co-authored-by: Takashi Kusumi <tkusumi@zlab.co.jp>

---------

Co-authored-by: Takashi Kusumi <tkusumi@zlab.co.jp>
  • Loading branch information
opensource21 and tksm committed Jul 14, 2023
1 parent dcba2dd commit d49142c
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 0 deletions.
2 changes: 2 additions & 0 deletions README.md
Expand Up @@ -155,6 +155,8 @@ functions](https://golang.org/pkg/text/template/#hdr-Functions)):
| `color` | `color.Color, string` | Wrap the text in color (.ContainerColor and .PodColor provided) |
| `parseJSON` | `string` | Parse string as JSON |
| `tryParseJSON` | `string` | Attempt to parse string as JSON, return nil on failure |
| `extractJSONParts` | `string, ...string` | Parse string as JSON and concatenate the given keys. |
| `tryExtractJSONParts` | `string, ...string` | Attempt to parse string as JSON and concatenate the given keys. , return text on failure |
| `extjson` | `string` | Parse the object as json and output colorized json |
| `ppextjson` | `string` | Parse the object as json and output pretty-print colorized json |
| `toRFC3339Nano` | `object` | Parse timestamp (string, int, json.Number) and output it using RFC3339Nano format |
Expand Down
22 changes: 22 additions & 0 deletions cmd/cmd.go
Expand Up @@ -450,6 +450,28 @@ func (o *options) generateTemplate() (*template.Template, error) {
}
return obj, nil
},
"extractJSONParts": func(text string, part ...string) (string, error) {
obj := make(map[string]interface{})
if err := json.Unmarshal([]byte(text), &obj); err != nil {
return "", err
}
parts := make([]string, 0)
for _, key := range part {
parts = append(parts, fmt.Sprintf("%v", obj[key]))
}
return strings.Join(parts, ", "), nil
},
"tryExtractJSONParts": func(text string, part ...string) string {
obj := make(map[string]interface{})
if err := json.Unmarshal([]byte(text), &obj); err != nil {
return text
}
parts := make([]string, 0)
for _, key := range part {
parts = append(parts, fmt.Sprintf("%v", obj[key]))
}
return strings.Join(parts, ", ")
},
"extjson": func(in string) (string, error) {
if json.Valid([]byte(in)) {
return strings.TrimSuffix(in, "\n"), nil
Expand Down

0 comments on commit d49142c

Please sign in to comment.