-
-
Notifications
You must be signed in to change notification settings - Fork 10
/
json.go
145 lines (125 loc) · 4.26 KB
/
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
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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
// SPDX-License-Identifier: Apache-2.0
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License 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 utils
import (
"bufio"
"bytes"
"encoding/json"
"fmt"
"io"
"strings"
)
const (
DEFAULT_JSON_INDENT_STRING = " "
DEFAULT_JSON_PREFIX_STRING = ""
)
func IsJsonMapType(any interface{}) (isMapType bool) {
_, isMapType = any.(map[string]interface{})
return
}
func IsJsonSliceType(any interface{}) (isSliceType bool) {
_, isSliceType = any.([]interface{})
return
}
func IsValidJsonRaw(test []byte) bool {
var js interface{}
err := json.Unmarshal(test, &js)
return err == nil
}
// NOTE: simple wrapper method on json package to standardize parms
// WARNING: By default, json.Marshal() methods will use a unicode encoding
// which will encode utf8 characters such as: '@', '<', '>', etc.
func MarshalAnyToFormattedJsonString(any interface{}) (string, error) {
// Indent each level with 2 space chars.
byteMapOut, err := json.MarshalIndent(any, "", " ")
return string(byteMapOut), err
}
func MarshalStructToJsonMap(any interface{}) (mapOut map[string]interface{}, err error) {
// TODO: validate input parameter is a struct
var bytesOut []byte
bytesOut, err = json.Marshal(any)
if err != nil {
return
}
err = json.Unmarshal(bytesOut, &mapOut)
return
}
func CalcLineAndCharacterPos(data []byte, offset int64) (lineNum int, charNum int) {
const LF byte = 0x0a
lineNum = 1
charNum = 0
intOffset := int(offset)
for i := 0; i < len(data) && i < intOffset; i, charNum = i+1, charNum+1 {
if data[i] == LF {
lineNum++
//fmt.Printf("NEWLINE (%v): total: %d, offset: %d\n", LF, line, char)
charNum = 0
}
}
return lineNum, charNum - 1
}
// Creates strings of spaces based upon provided integer length (e.g., the --indent <length> flag)
func GenerateIndentString(length int) (prefix string) {
var sb strings.Builder
for i := 0; i < length; i++ {
sb.WriteString(" ")
}
return sb.String()
}
// NOTE: Using this custom encoder avoids the json.Marshal() default
// behavior of encoding utf8 characters such as: '@', '<', '>', etc. as unicode.
func EncodeAnyToIndentedJSONStr(any interface{}, indent string) (outputBuffer bytes.Buffer, err error) {
bufferedWriter := bufio.NewWriter(&outputBuffer)
encoder := json.NewEncoder(bufferedWriter)
encoder.SetEscapeHTML(false)
encoder.SetIndent(DEFAULT_JSON_PREFIX_STRING, indent)
err = encoder.Encode(any)
// MUST ensure all data is written to buffer before further testing
bufferedWriter.Flush()
return
}
func EncodeAnyToDefaultIndentedJSONStr(any interface{}) (outputBuffer bytes.Buffer, err error) {
return EncodeAnyToIndentedJSONStr(any, DEFAULT_JSON_INDENT_STRING)
}
func EncodeAnyToIndentedJSONInt(any interface{}, numSpaces int) (outputBuffer bytes.Buffer, err error) {
indentString := GenerateIndentString(numSpaces)
return EncodeAnyToIndentedJSONStr(any, indentString)
}
func WriteAnyAsEncodedJSONInt(writer io.Writer, any interface{}, numSpaces int) (outputBuffer bytes.Buffer, err error) {
outputBuffer, err = EncodeAnyToIndentedJSONInt(any, numSpaces)
if writer != nil && err == nil {
_, err = writer.Write(outputBuffer.Bytes())
}
return
}
func PrintlnJSONObject(any interface{}) {
buffer, err := EncodeAnyToDefaultIndentedJSONStr(any)
if err == nil {
fmt.Printf("%s\n", buffer.String())
return
}
fmt.Printf("Print error: %s\n", err.Error())
}
func PrintlnLabeledJSONObject(any interface{}, label string) {
buffer, err := EncodeAnyToDefaultIndentedJSONStr(any)
if err == nil {
fmt.Printf("%s: %s\n", label, buffer.String())
return
}
fmt.Printf("Print error: %s\n", err.Error())
}