Skip to content

Latest commit

 

History

History
376 lines (334 loc) · 6.51 KB

README.md

File metadata and controls

376 lines (334 loc) · 6.51 KB

Go JSON utility library

GoDoc Go Report Card codecov

Install

$ go get github.com/Bhinneka/goson

Todo

  • Add more utility

Hide specific fields

package main

import (
	"encoding/json"
	"fmt"
	"os"
	"time"

	"github.com/Bhinneka/goson"
)

// Bhinnekaners type
type Bhinnekaners struct {
	ID        string    `json:"id"`
	FirstName string    `json:"firstName"`
	LastName  string    `json:"lastName"`
	BirthDate time.Time `json:"birthDate"`
	Created   time.Time `json:"created"`
	CreatorIP string    `json:"creatorIp"`
}

func main() {
	wury := &Bhinnekaners{
		ID:        "001",
		FirstName: "Wuriyanto",
		LastName:  "Musobar",
		BirthDate: time.Now(),
		Created:   time.Now(),
		CreatorIP: "10.0.1.1",
	}

	b1, err := json.Marshal(wury)
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}

	fmt.Println(string(b1))

    // hide specific field, eg: fields created and creatorIp
	result, err := goson.HideFields(*wury, "created", "creatorIp")

	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}

	b2, err := json.Marshal(result)
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}

	fmt.Println(string(b2))
}

before hide

{
	"id": "001",
	"firstName": "Wuriyanto",
	"lastName": "Musobar",
	"birthDate": "2019-02-12T11:07:20.68801+07:00",
	"created": "2019-02-12T11:07:20.68801+07:00",
	"creatorIp": "10.0.1.1"
}

after hide

{
	"id": "001",
	"lastName": "Musobar",
	"firstName": "Wuriyanto",
	"birthDate": "2019-02-12T11:12:04.5998+07:00"
}

Make Zero Omitempty

// Child type
type Child struct {
	ChildA      string `json:"childA"`
	ChildB      string `json:"childB,omitempty"`
	ChildStruct struct {
		A int `json:"A,omitempty"`
		B int `json:"B"`
	} `json:"childStruct"`
}
// arr type for slice example
type arr struct {
	Arr1 string `json:"arr1"`
	Arr2 string `json:"arr2,omitempty"`
}

// Bhinnekaners type
type Bhinnekaners struct {
	Name       string `json:"name"`
	Additional string `json:"additional,omitempty"`
	AddStruct  struct {
		Field1 string `json:"field1,omitempty"`
		Field2 string `json:"field2"`
	} `json:"addStruct"`
	AddChildPtr *Child `json:"child"`
	Slice       []arr  `json:"slice"`
}

example := Bhinnekaners{
	Name:       "Agung DP",
	Additional: "testing",
	AddStruct: struct {
		Field1 string `json:"field1,omitempty"`
		Field2 string `json:"field2"`
	}{
		Field1: "Field 1",
		Field2: "Field 2",
	},
	AddChildPtr: &Child{
		ChildA: "Child A",
		ChildB: "Child B",
		ChildStruct: struct {
			A int `json:"A,omitempty"`
			B int `json:"B"`
		}{
			A: 453,
			B: 567,
		},
	},
	Slice: []arr{
		arr{
			Arr1: "Test field slice 1",
			Arr2: "Test field slice 2",
		},
	},
}

json marshal before make zero field omitempty in example variable:

{
  "name": "Agung DP",
  "additional": "testing",
  "addStruct": {
    "field1": "Field 1",
    "field2": "Field 2"
  },
  "child": {
    "childA": "Child A",
    "childB": "Child B",
    "childStruct": {
      "A": 453,
      "B": 567
    }
  },
  "slice": [
    {
      "arr1": "Test field slice 1",
      "arr2": "Test field slice 2"
    }
  ]
}

json marshal after make zero field omitempty in example variable:

{
  "name": "Agung DP",
  "addStruct": {
    "field2": "Field 2"
  },
  "child": {
    "childA": "Child A",
    "childStruct": {
      "B": 567
    }
  },
  "slice": [
    {
      "arr1": "Test field slice 1"
    }
  ]
}

Advance JSON Unmarshal

package main

import (
	"fmt"
	"github.com/Bhinneka/goson"
)

type Slice struct {
	FieldA int    `json:"fieldA"`
	FieldB string `json:"fieldB"`
	Exist  string `json:"exist"`
}
type Model struct {
	ID        int     `json:"id"`
	Name      string  `json:"name"`
	MustFloat float64 `json:"mustFloat"`
	MustInt   int     `json:"mustInt"`
	IsExist   bool    `json:"isExist"`
	Obj       *struct {
		N       int `json:"n"`
		Testing struct {
			Ss int `json:"ss"`
		} `json:"testing"`
	} `json:"obj"`
	Slice []Slice `json:"slice"`
}

var data = []byte(`
{
	"id": "01",
	"name": "agungdp",
	"mustFloat": "2.23423",
	"mustInt": 2.23423,
	"isExist": "true",
	"obj": {
		"n": 2,
		"testing": {
			"ss": "23840923849284"
		}
	},
	"slice": [
		{
			"fieldA": "100",
			"fieldB": "3000",
			"exist": true
		},
		{
			"fieldA": 50000,
			"fieldB": "123000"
		}
	]
}
`)

func main() {
	var target Model
	goson.Unmarshal(data, &target)
	fmt.Printf("%+v\n", target)
}

Value from target:

{
     "id": 1,
     "name": "agungdp",
     "mustFloat": 2.23423,
     "mustInt": 2,
     "isExist": true,
     "obj": {
          "n": 2,
          "testing": {
               "ss": 23840923849284
          }
     },
     "slice": [
          {
               "fieldA": 100,
               "fieldB": "3000",
               "exist": "true"
          },
          {
               "fieldA": 50000,
               "fieldB": "123000",
               "exist": ""
          }
     ]
}

JSON Reader

package main

import (
	"fmt"
	"github.com/Bhinneka/goson"
)

var data = []byte(`
{
	"id": "0101",
	"name": "agungdp",
	"mustFloat": "2.23423",
	"mustInt": 2.23423,
	"uint": 11,
	"isExist": "true",
	"obj": {
		"n": 2,
		"testing": {
			"ss": "23840923849284"
		}
	},
	"slice": [
		{
			"fieldA": "100",
			"fieldB": 3000,
			"exist": true,
			"test": "3.14"
		},
		{
			"fieldA": 50000,
			"fieldB": "123000",
			"exist": 3000,
			"test": 1323.123
		}
	],
	"str": ["a", true],
	"ints": ["2", 3],
	"bools": [1, "true", "0", true],
	"NoTag": 19283091832
}
`)

func main() {
	reader, err := goson.Read(data)
	if err != nil {
		panic(err)
	}

	// get string field
	str, _ := reader.GetField("slice", "[1]", "fieldA").String()
	fmt.Printf("%s\n", str) // "50000"

	// get int field
	i, _ := reader.GetField("obj", "testing", "ss").Int()
	fmt.Printf("%d\n", i) // 23840923849284

	// get uint field
	u, _ := reader.GetField("uint").Uint()
	fmt.Printf("%d\n", u) // 11

	// get float field
	fl, _ := reader.GetField("slice", "[0]", "test").Float()
	fmt.Printf("%f\n", fl) // 3.14

	// get bool field
	b, _ := reader.GetField("isExist").Bool()
	fmt.Printf("%v\n", b) // true

	// get sub-json field (support object & array field)
	var m struct {
		SS string `json:"ss"`
	}
	reader.GetField("obj", "testing").SetTo(&m)
	fmt.Printf("%+v\n", m) // {SS: 23840923849284}
}