Skip to content

Commit

Permalink
added a json parser with the ability to specify a field whitelist
Browse files Browse the repository at this point in the history
  • Loading branch information
e-nikolov committed Jun 29, 2018
1 parent b43b3f2 commit 4acb943
Show file tree
Hide file tree
Showing 3 changed files with 162 additions and 0 deletions.
21 changes: 21 additions & 0 deletions xjson/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2016 Markus Ast

Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
'Software'), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
96 changes: 96 additions & 0 deletions xjson/xjson.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
package xjson

import (
"encoding/json"
"io"
"reflect"
"strings"
)

func Unmarshal(data []byte, v interface{}, whitelist ...string) error {
tmp := map[string]json.RawMessage{}

err := json.Unmarshal(data, &tmp)

if err != nil {
switch err {
case io.EOF:
return nil
default:
return err
}
}

fields := extract(v)

for _, name := range whitelist {
field, ok := fields[name]
if !ok {
continue
}

raw, ok := tmp[name]
if !ok {
continue
}

val := reflect.New(field.Type())
if err := json.Unmarshal(raw, val.Interface()); err != nil {
return err
}
field.Set(val.Elem())
}

return nil
}

func extract(dst interface{}) map[string]reflect.Value {
t := reflect.TypeOf(dst)
v := reflect.ValueOf(dst)

if t.Kind() == reflect.Ptr {
t = t.Elem()
v = v.Elem()
}

fields := map[string]reflect.Value{}
for i := 0; i < t.NumField(); i++ {
f := t.Field(i)
tags := strings.Split(f.Tag.Get("json"), ",")
name := ""
if len(tags) > 0 {
name = tags[0]
}
if name == "-" {
continue
}
if name == "" {
name = f.Name
}

fv := v.Field(i)

if f.Anonymous { // embedded struct
ft := f.Type
if ft.Kind() == reflect.Ptr {
ft = ft.Elem()
fv = fv.Elem()
}

if !fv.IsValid() { // eg. is nil
// init embedded struct
fv = reflect.New(ft)
v.Field(i).Set(fv)
fv = fv.Elem()
}

for k, v := range extract(fv.Addr().Interface()) {
fields[k] = v
}
}

fields[name] = fv
}

return fields
}
45 changes: 45 additions & 0 deletions xjson/xjson_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
package xjson_test

import (
"testing"

"github.com/unchainio/pkg/xjson"
"v/github.com/docker/[email protected]/pkg/testutil/assert"
)

type T struct {
A string
B string
}

type TestCase struct {
Data []byte
Whitelist []string
Expected *T
}

func TestUnmarshal(t *testing.T) {
cases := []TestCase{
{
Data: []byte("{\"A\": \"a\", \"B\":\"b\"}"),
Whitelist: []string{"A"},
Expected: &T{A: "a"},
},
{
Data: []byte("{\"A\": \"a\", \"B\":\"b\"}"),
Whitelist: []string{"B"},
Expected: &T{B: "b"},
},
{
Data: []byte("{\"A\": \"a\", \"B\":\"b\"}"),
Whitelist: []string{"A", "B"},
Expected: &T{A: "a", B: "b"},
},
}

for _, tc := range cases {
v := new(T)
xjson.Unmarshal(tc.Data, v, tc.Whitelist...)
assert.DeepEqual(t, v, tc.Expected)
}
}

0 comments on commit 4acb943

Please sign in to comment.