forked from aws/session-manager-plugin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
jsonutil.go
87 lines (78 loc) · 2.47 KB
/
jsonutil.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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
// Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License"). You may not
// use this file except in compliance with the License. A copy of the
// License is located at
//
// http://aws.amazon.com/apache2.0/
//
// or in the "license" file accompanying this file. This file is distributed
// on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
// either express or implied. See the License for the specific language governing
// permissions and limitations under the License.
// Package jsonutil contains various utilities for dealing with json data.
package jsonutil
import (
"bytes"
"encoding/json"
)
// jsonFormat json formatIndent
const jsonFormat = " "
// Indent indents a json string.
func Indent(jsonStr string) string {
var dst bytes.Buffer
json.Indent(&dst, []byte(jsonStr), "", jsonFormat)
return string(dst.Bytes())
}
// Remarshal marshals an object to Json then parses it back to another object.
// This is useful for example when we want to go from map[string]interface{}
// to a more specific struct type or if we want a deep copy of the object.
func Remarshal(obj interface{}, remarshalledObj interface{}) (err error) {
b, err := json.Marshal(obj)
if err != nil {
return
}
err = json.Unmarshal(b, remarshalledObj)
if err != nil {
return
}
return nil
}
// Marshal marshals an object to a json string.
// Returns empty string if marshal fails.
func Marshal(obj interface{}) (result string, err error) {
var resultB []byte
resultB, err = json.Marshal(obj)
if err != nil {
return
}
result = string(resultB)
return
}
// UnmarshalFile reads the content of a file then Unmarshals the content to an object.
func UnmarshalFile(filePath string, dest interface{}) (err error) {
content, err := ioUtil.ReadFile(filePath)
if err != nil {
return
}
err = json.Unmarshal(content, dest)
return
}
// Unmarshal unmarshals the content in string format to an object.
func Unmarshal(jsonContent string, dest interface{}) (err error) {
content := []byte(jsonContent)
err = json.Unmarshal(content, dest)
return
}
// MarshalIndent is like Marshal but applies Indent to format the output.
// Returns empty string if marshal fails
func MarshalIndent(obj interface{}) (result string, err error) {
var resultsByte []byte
// Make sure the output file keeps formal json format
resultsByte, err = json.MarshalIndent(obj, "", jsonFormat)
if err != nil {
return
}
result = string(resultsByte)
return
}