forked from hyperledger-archives/aries-framework-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjson.go
121 lines (97 loc) · 2.28 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
/*
Copyright SecureKey Technologies Inc. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
package verifiable
import (
"encoding/json"
)
// marshalWithCustomFields marshals value merged with custom fields defined in the map into JSON bytes.
func marshalWithCustomFields(v interface{}, cf map[string]interface{}) ([]byte, error) {
// Merge value and custom fields into the joint map.
vm, err := mergeCustomFields(v, cf)
if err != nil {
return nil, err
}
// Marshal the joint map.
return json.Marshal(vm)
}
// unmarshalWithCustomFields unmarshals JSON into value v and puts all JSON fields which do not belong to value
// into custom fields map cf.
func unmarshalWithCustomFields(data []byte, v interface{}, cf map[string]interface{}) error {
err := json.Unmarshal(data, v)
if err != nil {
return err
}
// Collect value fields map.
vData, err := json.Marshal(v)
if err != nil {
return err
}
var vf map[string]interface{}
err = json.Unmarshal(vData, &vf)
if err != nil {
return err
}
// Collect all fields map.
var af map[string]interface{}
err = json.Unmarshal(data, &af)
if err != nil {
return err
}
// Copy only those entries which do not belong to the value (i.e. custom fields).
for k, v := range af {
if _, ok := vf[k]; !ok {
cf[k] = v
}
}
return nil
}
// mergeCustomFields converts value to the JSON-like map and merges it with custom fields map cf.
func mergeCustomFields(v interface{}, cf map[string]interface{}) (map[string]interface{}, error) {
kf, err := toMap(v)
if err != nil {
return nil, err
}
// Supplement value map with custom fields.
for k, v := range cf {
if _, exists := kf[k]; !exists {
kf[k] = v
}
}
return kf, nil
}
func toMap(v interface{}) (map[string]interface{}, error) {
var (
b []byte
err error
)
switch cv := v.(type) {
case []byte:
b = cv
case string:
b = []byte(cv)
default:
b, err = json.Marshal(v)
if err != nil {
return nil, err
}
}
var m map[string]interface{}
err = json.Unmarshal(b, &m)
if err != nil {
return nil, err
}
return m, nil
}
func toMaps(v []interface{}) ([]map[string]interface{}, error) {
maps := make([]map[string]interface{}, len(v))
for i := range v {
m, err := toMap(v[i])
if err != nil {
return nil, err
}
maps[i] = m
}
return maps, nil
}