-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathjson.go
40 lines (33 loc) · 1.05 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
// Copyright 2021-2024 Nokia
// Licensed under the BSD 3-Clause License.
// SPDX-License-Identifier: BSD-3-Clause
package restful
import (
"regexp"
"strings"
)
var reNull = regexp.MustCompile(`"[^"]+":null,?`)
var reEmptyArray = regexp.MustCompile(`"[^"]+":\[\],?`)
var reEmptyStruct = regexp.MustCompile(`"[^"]+":{},?`)
var reEmptyString = regexp.MustCompile(`"[^"]+":"",?`)
// SanitizeJSONString clears empty entries from string of JSON.
// Note that normally one should use "omitempty" in structures, and use pointers for arrays and structs.
// So sanitizing is not really needed.
func SanitizeJSONString(s string) string {
s = reNull.ReplaceAllString(s, "$1")
s = reEmptyArray.ReplaceAllString(s, "")
s = reEmptyString.ReplaceAllString(s, "")
var slen int
for {
slen = len(s)
s = reEmptyStruct.ReplaceAllString(s, "")
if slen == len(s) {
break
}
}
return strings.ReplaceAll(s, ",}", "}")
}
// SanitizeJSONBytes clears empty entries from byte array of JSON.
func SanitizeJSONBytes(b []byte) []byte {
return []byte(SanitizeJSONString(string(b)))
}