Skip to content

Commit 09562fd

Browse files
committed
feat: encoding/jsonutil/jsonraw: add ObjectModify()`
1 parent 89bedbd commit 09562fd

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
package jsonutil
2+
3+
import (
4+
"encoding/json"
5+
)
6+
7+
// ObjectModify creates a new byte slice, from an existing byte slice, with only the supplied field names.
8+
func ObjectModify(b []byte, fieldNamesInclCopy []string, fieldNameInclUpsertValues map[string]any) ([]byte, error) {
9+
msa := map[string]any{}
10+
err := json.Unmarshal(b, &msa)
11+
if err != nil {
12+
return []byte{}, err
13+
}
14+
if len(msa) == 0 {
15+
return b, nil
16+
}
17+
incl := map[string]int{}
18+
for _, f := range fieldNamesInclCopy {
19+
incl[f]++
20+
}
21+
out := map[string]any{}
22+
for k, v := range msa {
23+
if _, ok := incl[k]; ok {
24+
out[k] = v
25+
}
26+
}
27+
for k, v := range fieldNameInclUpsertValues {
28+
out[k] = v
29+
}
30+
return json.Marshal(out)
31+
}

0 commit comments

Comments
 (0)