goson

package module
v0.0.0-...-e51dfca Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 20, 2019 License: Apache-2.0 Imports: 6 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

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}
}

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func HideFields

func HideFields(input interface{}, fields ...string) (map[string]interface{}, error)

HideFields will hide json field based on struct json field you choose params - input (struct only) - fields json field that you will be hide

func MakeZeroOmitempty

func MakeZeroOmitempty(obj interface{}) (err error)

MakeZeroOmitempty tools for make Zero value in field contains `json: omitempty` tag

func Unmarshal

func Unmarshal(data []byte, target interface{}) (err error)

Unmarshal json string, avoid error if incompatible data type

Types

type Field

type Field interface {
	Uint() (uint, error)
	Int() (int, error)
	String() (string, error)
	Float() (float64, error)
	Bool() (bool, error)
	SetTo(target interface{}) error
}

Field from json reader

type Reader

type Reader interface {
	GetField(keys ...string) Field
}

Reader json string

func Read

func Read(data []byte) (Reader, error)

Read from json input

Directories

Path Synopsis
_examples
json_hide command
json_omitempty command
json_unmarshal command

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL