mirror of
https://codeberg.org/scip/tablizer.git
synced 2025-12-16 20:20:57 +01:00
Fix json parser (#80)
* fix #77: parse floats and nils as well and convert them to string
This commit is contained in:
@@ -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"
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
Reference in New Issue
Block a user