Skip to content

Commit d49142c

Browse files
opensource21Takashi Kusumi
andauthored
Possibility to extract parts of a json-message. (#271)
* 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>
1 parent dcba2dd commit d49142c

File tree

2 files changed

+24
-0
lines changed

2 files changed

+24
-0
lines changed

README.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -155,6 +155,8 @@ functions](https://golang.org/pkg/text/template/#hdr-Functions)):
155155
| `color` | `color.Color, string` | Wrap the text in color (.ContainerColor and .PodColor provided) |
156156
| `parseJSON` | `string` | Parse string as JSON |
157157
| `tryParseJSON` | `string` | Attempt to parse string as JSON, return nil on failure |
158+
| `extractJSONParts` | `string, ...string` | Parse string as JSON and concatenate the given keys. |
159+
| `tryExtractJSONParts` | `string, ...string` | Attempt to parse string as JSON and concatenate the given keys. , return text on failure |
158160
| `extjson` | `string` | Parse the object as json and output colorized json |
159161
| `ppextjson` | `string` | Parse the object as json and output pretty-print colorized json |
160162
| `toRFC3339Nano` | `object` | Parse timestamp (string, int, json.Number) and output it using RFC3339Nano format |

cmd/cmd.go

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -450,6 +450,28 @@ func (o *options) generateTemplate() (*template.Template, error) {
450450
}
451451
return obj, nil
452452
},
453+
"extractJSONParts": func(text string, part ...string) (string, error) {
454+
obj := make(map[string]interface{})
455+
if err := json.Unmarshal([]byte(text), &obj); err != nil {
456+
return "", err
457+
}
458+
parts := make([]string, 0)
459+
for _, key := range part {
460+
parts = append(parts, fmt.Sprintf("%v", obj[key]))
461+
}
462+
return strings.Join(parts, ", "), nil
463+
},
464+
"tryExtractJSONParts": func(text string, part ...string) string {
465+
obj := make(map[string]interface{})
466+
if err := json.Unmarshal([]byte(text), &obj); err != nil {
467+
return text
468+
}
469+
parts := make([]string, 0)
470+
for _, key := range part {
471+
parts = append(parts, fmt.Sprintf("%v", obj[key]))
472+
}
473+
return strings.Join(parts, ", ")
474+
},
453475
"extjson": func(in string) (string, error) {
454476
if json.Valid([]byte(in)) {
455477
return strings.TrimSuffix(in, "\n"), nil

0 commit comments

Comments
 (0)