client-go: change jsonpath output of non-primitive types from Go-syntax to JSON

kubectl: add --output jsonpath-as-json to print a json array of results
kubeadm: fix test case using jsonpath result of non-primitive type

Kubernetes-commit: ba386aba4fe02906089ca3e96ee07925bced5d4d
This commit is contained in:
Phil Ferrell
2020-04-15 14:45:44 -07:00
committed by Kubernetes Publisher
parent 5159cff060
commit bd76c10336
2 changed files with 146 additions and 10 deletions

View File

@@ -18,6 +18,7 @@ package jsonpath
import (
"bytes"
"encoding/json"
"fmt"
"io"
"reflect"
@@ -36,6 +37,7 @@ type JSONPath struct {
lastEndNode *Node
allowMissingKeys bool
outputJSON bool
}
// New creates a new JSONPath with the given name.
@@ -125,10 +127,49 @@ func (j *JSONPath) FindResults(data interface{}) ([][]reflect.Value, error) {
return fullResult, nil
}
// EnableJSONOutput changes the PrintResults behavior to return a JSON array of results
func (j *JSONPath) EnableJSONOutput(v bool) {
j.outputJSON = v
}
// PrintResults writes the results into writer
func (j *JSONPath) PrintResults(wr io.Writer, results []reflect.Value) error {
if j.outputJSON {
// convert the []reflect.Value to something that json
// will be able to marshal
r := make([]interface{}, 0, len(results))
for i := range results {
r = append(r, results[i].Interface())
}
results = []reflect.Value{reflect.ValueOf(r)}
}
for i, r := range results {
text, err := j.evalToText(r)
var text []byte
var err error
outputJSON := true
kind := r.Kind()
if kind == reflect.Interface {
kind = r.Elem().Kind()
}
switch kind {
case reflect.Map:
case reflect.Array:
case reflect.Slice:
case reflect.Struct:
default:
outputJSON = false
}
switch {
case outputJSON || j.outputJSON:
if j.outputJSON {
text, err = json.MarshalIndent(r.Interface(), "", " ")
text = append(text, '\n')
} else {
text, err = json.Marshal(r.Interface())
}
default:
text, err = j.evalToText(r)
}
if err != nil {
return err
}
@@ -139,7 +180,9 @@ func (j *JSONPath) PrintResults(wr io.Writer, results []reflect.Value) error {
return err
}
}
return nil
}
// walk visits tree rooted at the given node in DFS order