forked from rackspace/rack
/
json.go
43 lines (36 loc) · 961 Bytes
/
json.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
package output
import (
"encoding/json"
"fmt"
"io"
)
// INDENT is the indentation passed to json.MarshalIndent
const INDENT string = " "
func limitJSONFields(m map[string]interface{}, keys []string) map[string]interface{} {
mLimited := make(map[string]interface{})
for _, key := range keys {
if v, ok := m[key]; ok {
mLimited[key] = v
}
}
return mLimited
}
func jsonOut(w io.Writer, i interface{}) {
j, _ := json.MarshalIndent(i, "", INDENT)
fmt.Fprintln(w, string(j))
}
func DefaultJSON(w io.Writer, i interface{}) {
m := map[string]interface{}{"result": i}
jsonOut(w, m)
}
func MetadataJSON(w io.Writer, m map[string]interface{}, keys []string) {
mLimited := limitJSONFields(m, keys)
jsonOut(w, mLimited)
}
func ListJSON(w io.Writer, maps []map[string]interface{}, keys []string) {
mLimited := make([]map[string]interface{}, len(maps))
for i, m := range maps {
mLimited[i] = limitJSONFields(m, keys)
}
jsonOut(w, mLimited)
}