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 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184
|
package toolbox
import (
"bytes"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"strings"
)
//IsStructuredJSON returns true if supplied represent JSON structure (map,array)
func IsStructuredJSON(candidate string) bool {
candidate = strings.Trim(candidate, "\n \t\r")
if candidate == "" {
return false
}
curlyStart := strings.Count(candidate, "{")
curlyEnd := strings.Count(candidate, "}")
squareStart := strings.Count(candidate, "[")
squareEnd := strings.Count(candidate, "]")
if !(curlyStart == curlyEnd && squareStart == squareEnd) || (curlyStart+squareStart == 0) {
return false
}
if !(strings.HasPrefix(candidate, "{") && strings.HasSuffix(candidate, "}") || strings.HasPrefix(candidate, "[") && strings.HasSuffix(candidate, "]")) {
return false
}
return json.Valid([]byte(candidate))
}
//IsCompleteJSON returns true if supplied represent complete JSON
func IsCompleteJSON(candidate string) bool {
return json.Valid([]byte(candidate))
}
//NewLineDelimitedJSON returns JSON for supplied multi line JSON
func NewLineDelimitedJSON(candidate string) ([]interface{}, error) {
var result = make([]interface{}, 0)
lines := getMultilineContent(candidate)
for _, line := range lines {
aStruct, err := JSONToInterface(line)
if err != nil {
return nil, err
}
result = append(result, aStruct)
}
return result, nil
}
func getMultilineContent(multiLineText string) []string {
multiLineText = strings.TrimSpace(multiLineText)
if multiLineText == "" {
return []string{}
}
lines := strings.Split(multiLineText, "\n")
var result = make([]string, 0)
for _, line := range lines {
if strings.Trim(line, " \r") == "" {
continue
}
result = append(result, line)
}
return result
}
//IsNewLineDelimitedJSON returns true if supplied content is multi line delimited JSON
func IsNewLineDelimitedJSON(candidate string) bool {
lines := getMultilineContent(candidate)
if len(lines) <= 1 {
return false
}
return IsStructuredJSON(lines[0]) && IsStructuredJSON(lines[1])
}
//JSONToInterface converts JSON source to an interface (either map or slice)
func JSONToInterface(source interface{}) (interface{}, error) {
var reader io.Reader
switch value := source.(type) {
case io.Reader:
reader = value
case []byte:
reader = bytes.NewReader(value)
case string:
reader = strings.NewReader(value)
default:
return nil, fmt.Errorf("unsupported type: %T", source)
}
var result interface{}
if content, err := ioutil.ReadAll(reader); err == nil {
text := string(content)
if IsNewLineDelimitedJSON(text) {
return NewLineDelimitedJSON(text)
}
reader = strings.NewReader(text)
}
err := jsonDecoderFactory{}.Create(reader).Decode(&result)
return result, err
}
//JSONToMap converts JSON source into map
func JSONToMap(source interface{}) (map[string]interface{}, error) {
var reader io.Reader
switch value := source.(type) {
case io.Reader:
reader = value
case []byte:
reader = bytes.NewReader(value)
case string:
reader = strings.NewReader(value)
default:
return nil, fmt.Errorf("unsupported type: %T", source)
}
var result = make(map[string]interface{})
err := jsonDecoderFactory{}.Create(reader).Decode(&result)
return result, err
}
//JSONToSlice converts JSON source into slice
func JSONToSlice(source interface{}) ([]interface{}, error) {
var reader io.Reader
switch value := source.(type) {
case io.Reader:
reader = value
case []byte:
reader = bytes.NewReader(value)
case string:
reader = strings.NewReader(value)
default:
return nil, fmt.Errorf("unsupported type: %T", source)
}
var result = make([]interface{}, 0)
err := jsonDecoderFactory{}.Create(reader).Decode(&result)
return result, err
}
//AsJSONText converts data structure int text JSON
func AsJSONText(source interface{}) (string, error) {
if source == nil {
return "", fmt.Errorf("source was nil")
}
if IsStruct(source) || IsMap(source) || IsSlice(source) {
buf := new(bytes.Buffer)
err := NewJSONEncoderFactory().Create(buf).Encode(source)
return buf.String(), err
}
return "", fmt.Errorf("unsupported type: %T", source)
}
//AsIndentJSONText converts data structure int text JSON
func AsIndentJSONText(source interface{}) (string, error) {
if IsStruct(source) || IsMap(source) || IsSlice(source) {
buf, err := json.MarshalIndent(source, "", "\t")
if err != nil {
return "", err
}
return string(buf), nil
}
return "", fmt.Errorf("unsupported type: %T", source)
}
//AnyJSONType represents any JSON type
type AnyJSONType string
//UnmarshalJSON implements unmarshalerinterface
func (s *AnyJSONType) UnmarshalJSON(b []byte) error {
*s = AnyJSONType(b)
return nil
}
//MarshalJSON implements marshaler interface
func (s *AnyJSONType) MarshalJSON() ([]byte, error) {
if len(*s) == 0 {
return []byte(`""`), nil
}
return []byte(*s), nil
}
//Value returns string or string slice value
func (s AnyJSONType) Value() (interface{}, error) {
var result interface{}
return result, json.Unmarshal([]byte(s), &result)
}
|