From 35b726fee4e1bc64612fdedf7de8894b080f93ee Mon Sep 17 00:00:00 2001 From: "T.v.Dein" Date: Mon, 6 Oct 2025 22:54:31 +0200 Subject: [PATCH] Fix json parser (#80) * fix #77: parse floats and nils as well and convert them to string --- cfg/config.go | 2 +- lib/parser.go | 29 +++++++++++++++++++++++++++++ lib/parser_test.go | 32 ++++++++++++++++++++++++++++++++ 3 files changed, 62 insertions(+), 1 deletion(-) diff --git a/cfg/config.go b/cfg/config.go index f30e6eb..ca7da0b 100644 --- a/cfg/config.go +++ b/cfg/config.go @@ -28,7 +28,7 @@ import ( ) const DefaultSeparator string = `(\s\s+|\t)` -const Version string = "v1.5.7" +const Version string = "v1.5.8" const MAXPARTS = 2 var DefaultConfigfile = os.Getenv("HOME") + "/.config/tablizer/config" diff --git a/lib/parser.go b/lib/parser.go index 2731e85..ef77148 100644 --- a/lib/parser.go +++ b/lib/parser.go @@ -25,6 +25,7 @@ import ( "fmt" "io" "log" + "math" "regexp" "strings" @@ -222,6 +223,32 @@ func parseRawJSON(conf cfg.Config, input io.Reader) (Tabdata, error) { row[idxmap[currentfield]] = val } } + + case float64: + var value string + + // we set precision to 0 if the float is a whole number + if val == math.Trunc(val) { + value = fmt.Sprintf("%.f", val) + } else { + value = fmt.Sprintf("%f", val) + } + + if !haveheaders { + row = append(row, value) + } else { + row[idxmap[currentfield]] = value + } + + case nil: + // we ignore here if a value shall be an int or a string, + // because tablizer only works with strings anyway + if !haveheaders { + row = append(row, "") + } else { + row[idxmap[currentfield]] = "" + } + case json.Delim: if val.String() == "}" { data = append(data, row) @@ -240,6 +267,8 @@ func parseRawJSON(conf cfg.Config, input io.Reader) (Tabdata, error) { haveheaders = true } isjson = true + default: + fmt.Printf("unknown token: %v type: %T\n", t, t) } iskey = !iskey diff --git a/lib/parser_test.go b/lib/parser_test.go index ce252a0..652680e 100644 --- a/lib/parser_test.go +++ b/lib/parser_test.go @@ -180,6 +180,38 @@ func TestParserJSONInput(t *testing.T) { expect: Tabdata{}, }, + { + // contains nil, int and float values + name: "niljson", + wanterror: false, + input: `[ + { + "NAME": "postgres-operator-7f4c7c8485-ntlns", + "READY": "1/1", + "STATUS": "Running", + "RESTARTS": 0, + "AGE": null, + "X": 12, + "Y": 34.222 + } +]`, + expect: Tabdata{ + columns: 7, + headers: []string{"NAME", "READY", "STATUS", "RESTARTS", "AGE", "X", "Y"}, + entries: [][]string{ + []string{ + "postgres-operator-7f4c7c8485-ntlns", + "1/1", + "Running", + "0", + "", + "12", + "34.222000", + }, + }, + }, + }, + { // one field missing + different order // but shall not fail