jsongo

package module
v1.1.1 Latest Latest
Warning

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

Go to latest
Published: Jun 8, 2021 License: MIT Imports: 9 Imported by: 6

README

jsongo

Jsongo is a simple library for golang to help you build Json without static struct or map[string]interface

json.Marshal and json.Unmarshal have never been that easy

If you had only one function to look at, look at the "At" function

If you want an easy way to turn your json into a structure you should use the "Print" function after unmarshalling json in a Node

[2021/06/08] Project is not dead. We are using it quite often. We haven't found any necessary update

You can find the doc on godoc.org GoDoc

Node

Node is the basic Structure that you must use when using jsongo. It can either be a:

  • Map (jsongo.TypeMap)
  • Array (jsongo.TypeArray)
  • Value (jsongo.TypeValue) Precisely a pointer store in an interface{}
  • Undefined (jsongo.TypeUndefined) default type

When a Node Type is set you cant change it without using Unset() first


Val
Synopsis:

turn this Node to TypeValue and set that value

func (that *Node) Val(val interface{}) 
Examples
code:
package main

import (
    "github.com/bennyscetbun/jsongo"
)

func main() {
    root := jsongo.Node{}
	root.Val(42)
	root.DebugPrint("")
}
output:
42
code:
package main

import (
    "github.com/bennyscetbun/jsongo"
)
type MyStruct struct {
	Member1 string
	Member2 int
}

func main() {
	root := jsongo.Node{}
	root.Val(MyStruct{"The answer", 42})
	root.DebugPrint("")
}
output:
{
  "Member1": "The answer",
  "Member2": 42
}

Array
Synopsis:

Turn this Node to a TypeArray and/or set the array size (reducing size will make you loose data)

func (that *Node) Array(size int) *[]Node
Examples
code:
package main

import (
    "github.com/bennyscetbun/jsongo"
)

func main() {
    root := jsongo.Node{}
	a := root.Array(4)
    for i := 0; i < 4; i++ {
        (*a)[i].Val(i)
    }
	root.DebugPrint("")
}
output:
[
  0,
  1,
  2,
  3
]
code:
package main

import (
    "github.com/bennyscetbun/jsongo"
)

func main() {
    root := jsongo.Node{}
    a := root.Array(4)
    for i := 0; i < 4; i++ {
        (*a)[i].Val(i)
    }
    root.Array(2) //Here we reduce the size and we loose some data
	root.DebugPrint("")
}
output:
[
  0,
  1
]

Map
Synopsis:

Turn this Node to a TypeMap and/or Create a new element for key if necessary and return it

func (that *Node) Map(key string) *Node
Examples
code:
package main

import (
    "github.com/bennyscetbun/jsongo"
)

func main() {
    root := jsongo.Node{}
    root.Map("there").Val("you are")
    root.Map("here").Val("you should be")
	root.DebugPrint("")
}
output:
{
  "here": "you should be",
  "there": "you are"
}

At
Synopsis:

Helps you move through your node by building them on the fly

val can be string or int only

strings are keys for TypeMap

ints are index in TypeArray (it will make array grow on the fly, so you should start to populate with the biggest index first)

func (that *Node) At(val ...interface{}) *Node
Examples
code:
package main

import (
    "github.com/bennyscetbun/jsongo"
)

func main() {
    root := jsongo.Node{}
    root.At(4, "Who").Val("Let the dog out") //is equivalent to (*root.Array(5))[4].Map("Who").Val("Let the dog out")
    root.DebugPrint("")
}
output:
[
  null,
  null,
  null,
  null,
  {
    "Who": "Let the dog out"
  }
]
code:
package main

import (
    "github.com/bennyscetbun/jsongo"
)

func main() {
    root := jsongo.Node{}
    root.At(4, "Who").Val("Let the dog out")
    //to win some time you can even even save a certain Node
	node := root.At(2, "What")
	node.At("Can", "You").Val("do with that?")
	node.At("Do", "You", "Think").Val("Of that")
    root.DebugPrint("")
}
output:
[
  null,
  null,
  {
    "What": {
      "Can": {
        "You": "do with that?"
      },
      "Do": {
        "You": {
          "Think": "Of that"
        }
      }
    }
  },
  null,
  {
    "Who": "Let the dog out"
  }
]

Print
Synopsis:

Helps you build your code by printing a go structure from the json you ve just unmarshaled

func (that *Node) Print()

Other Function

There is plenty of other function, you should check the complete doc GoDoc

A last Example for fun
code:
package main

import (
    "github.com/bennyscetbun/jsongo"
)

func ShowOnlyValue(current *jsongo.Node) {
    switch current.GetType() {
    	case jsongo.TypeValue:
			println(current.Get().(string))
		case jsongo.TypeMap:
			for _, key := range current.GetKeys() {
				ShowOnlyValue(current.At(key))
			}
		case jsongo.TypeArray:
			for _, key := range current.GetKeys() {
				ShowOnlyValue(current.At(key))
			}
	}
}

func main() {
    root := jsongo.Node{}
    root.At(4, "Who").Val("Let the dog out")
	node := root.At(2, "What")
	node.At("Can", "You").Val("do with that?")
	node.At("Do", "You", "Think").Val("Of that")
	ShowOnlyValue(&root)
}
output:
Of that
do with that?
Let the dog out


Json Marshal/Unmarshal

One of the main purpose of jsongo was to create Json from data without using static structure or map[string]interface.

You can use the full power of the encoding/json package with jsongo.

Marshal
Example
code:
package main

import (
    "encoding/json"
	"fmt"
    "github.com/bennyscetbun/jsongo"
)

type Test struct {
	Static string `json:"static"`
	Over int `json:"over"`
}

func main() {
	root := jsongo.Node{}
	root.At("A", "AA", "AAA").Val(42)

	node := root.At("A", "AB")
	node.At(1).Val("Peace")
	node.At(0).Val(Test{"struct suck when you build json", 9000})
	root.At("B").Val("Oh Yeah")

	tojson, err := json.MarshalIndent(&root, "", "  ")
	if err != nil {
		fmt.Printf("%s\n", err.Error())
		return
	}
	fmt.Printf("%s\n", tojson)
}
output:
{
  "A": {
    "AA": {
      "AAA": 42
    },
    "AB": [
      {
        "static": "struct suck when you build json",
        "over": 9000
      },
      "Peace"
    ]
  },
  "B": "Oh Yeah"
}

Unmarshal

Unmarshal using Node follow some simple rules:

  • Any TypeUndefined Node will be set to the right type, any other type wont be changed
  • Array will grow if necessary
  • New keys will be added to Map
  • Values set to nil ".Val(nil)" will be turn into the type decide by Json
  • It will respect any current mapping and will return errors if needed

You can set a node as "DontExpand" with the UnmarshalDontExpand function and thoose rules will apply:

  • The type wont be change for any type
  • Array wont grow
  • New keys wont be added to Map
  • Values set to nil ".Val(nil)" will be turn into the type decide by Json
  • It will respect any current mapping and will return errors if needed
Example of full expand
code:
package main

import (
    "encoding/json"
    "github.com/bennyscetbun/jsongo"
    "fmt"
)

func main() {
    root := jsongo.Node{}
    fromjson := `{
	  "A": {
		"AA": {
		  "AAA": 42
		},
		"AB": [
		  {
			"static": "struct suck when you build json",
			"over": 9000
		  },
		  "Peace"
		]
	  },
	  "B": "Oh Yeah"
	}`
    err := json.Unmarshal([]byte(fromjson), &root)
	if err != nil {
		fmt.Printf("%s\n", err.Error())
		return
	}
	root.DebugProspect(0, "\t")
}
output:
Is of Type: TypeMap
A:
        Is of Type: TypeMap
        AA:
                Is of Type: TypeMap
                AAA:
                        Is of Type: TypeValue
                        Value of type: float64
                        42
        AB:
                Is of Type: TypeArray
                [0]:
                        Is of Type: TypeMap
                        static:
                                Is of Type: TypeValue
                                Value of type: string
                                struct suck when you build json
                        over:
                                Is of Type: TypeValue
                                Value of type: float64
                                9000
                [1]:
                        Is of Type: TypeValue
                        Value of type: string
                        Peace
B:
        Is of Type: TypeValue
        Value of type: string
        Oh Yeah
Example expand with mapping
code:
package main

import (
    "encoding/json"
    "github.com/bennyscetbun/jsongo"
    "fmt"
)
type Test struct {
    Static string `json:"static"`
    Over int `json:"over"`
}

func main() {
	root := jsongo.Node{}
    fromjson := `{
      "A": {
		"AA": {
		  "AAA": 42
		},
		"AB": [
		  {
			"static": "struct suck when you build json",
			"over": 9000
		  },
		  "Peace"
		]
	  },
	  "B": "Oh Yeah"
	}`
	root.At("A", "AB", 0).Val(Test{})
    err := json.Unmarshal([]byte(fromjson), &root)
	if err != nil {
		fmt.Printf("%s\n", err.Error())
		return
	}
	root.DebugProspect(0, "\t")
}
output:
Is of Type: TypeMap
A:
        Is of Type: TypeMap
        AB:
                Is of Type: TypeArray
                [0]:
                        Is of Type: TypeValue
                        Value of type: main.Test
                        {Static:struct suck when you build json Over:9000}
                [1]:
                        Is of Type: TypeValue
                        Value of type: string
                        Peace
        AA:
                Is of Type: TypeMap
                AAA:
                        Is of Type: TypeValue
                        Value of type: float64
                        42
B:
        Is of Type: TypeValue
        Value of type: string
        Oh Yeah
Example expand with some UnmarshalDontExpand
code:
package main

import (
    "encoding/json"
    "github.com/bennyscetbun/jsongo"
    "fmt"
)
type Test struct {
	Static string `json:"static"`
	Over int `json:"over"`
}

func main() {
    root := jsongo.Node{}
    fromjson := `{
      "A": {
		"AA": {
		  "AAA": 42
		},
		"AB": [
		  {
			"static": "struct suck when you build json",
			"over": 9000
		  },
		  "Peace"
		]
	  },
	  "B": "Oh Yeah"
	}`
	root.At("A", "AB").UnmarshalDontExpand(true, false).At(0).Val(Test{})
    err := json.Unmarshal([]byte(fromjson), &root)
	if err != nil {
		fmt.Printf("%s\n", err.Error())
		return
	}
	root.DebugProspect(0, "\t")
}
output:
Is of Type: TypeMap
A:
        Is of Type: TypeMap
        AB:
                Is of Type: TypeArray
                [0]:
                        Is of Type: TypeValue
                        Value of type: main.Test
                        {Static:struct suck when you build json Over:9000}
        AA:
                Is of Type: TypeMap
                AAA:
                        Is of Type: TypeValue
                        Value of type: float64
                        42
B:
        Is of Type: TypeValue
        Value of type: string
        Oh Yeah

Documentation

Index

Constants

This section is empty.

Variables

View Source
var ErrorArrayNegativeValue = errors.New("jsongo negative index for array")

ErrorArrayNegativeValue error if you ask for a negative index in an array

View Source
var ErrorAtUnsupportedType = errors.New("jsongo Unsupported Type as At argument")

ErrorArrayNegativeValue error if you ask for a negative index in an array

View Source
var ErrorCopyType = errors.New("jsongo: Copy: This Node is not a TypeUndefined")

ErrorCopyType error if you try to call Copy on a Node that isnt a TypeUndefined

View Source
var ErrorDeleteKey = errors.New("jsongo: DelKey: This Node is not a TypeMap")

ErrorDeleteKey error if you try to call DelKey on a Node that isnt a TypeMap

View Source
var ErrorGetKeys = errors.New("jsongo: GetKeys: Node is not a TypeMap or TypeArray")

ErrorGetKeys error if you try to get the keys from a Node that isnt a TypeMap or a TypeArray

View Source
var ErrorKeyAlreadyExist = errors.New("jsongo key already exist")

ErrorKeyAlreadyExist error if a key already exist in current Node

View Source
var ErrorMultipleType = errors.New("jsongo this node is already set to a different NodeType")

ErrorMultipleType error if a Node already got a different type of value

View Source
var ErrorRetrieveUserValue = errors.New("jsongo Cannot retrieve node's value which is not of type value")

ErrorRetrieveUserValue error if you ask the value of a node that is not a value node

View Source
var ErrorTypeUnmarshaling = errors.New("jsongo Wrong type when Unmarshaling")

ErrorTypeUnmarshaling error if you try to unmarshal something in the wrong type

View Source
var ErrorUnknowType = errors.New("jsongo Unknow NodeType")

ErrorUnknowType error if you try to use an unknow NodeType

View Source
var ErrorValNotPointer = errors.New("jsongo: Val: arguments must be a pointer and not nil")

ErrorValNotPointer error if you try to use Val without a valid pointer

Functions

func UpperCamelCase

func UpperCamelCase(str string) string

UpperCamelCase converts a string to it's upper camel case version.

Types

type Node added in v1.1.0

type Node struct {
	// contains filtered or unexported fields
}

Node Datastructure to build and maintain Nodes

func (*Node) Array added in v1.1.0

func (that *Node) Array(size int) *[]Node

Array Turn this Node to a TypeArray and/or set the array size (reducing size will make you loose data)

func (*Node) At added in v1.1.0

func (that *Node) At(val ...interface{}) *Node

At helps you move through your node by building them on the fly

val can be string or int only

strings are keys for TypeMap

ints are index in TypeArray (it will make array grow on the fly, so you should start to populate with the biggest index first)*

func (*Node) Copy added in v1.1.0

func (that *Node) Copy(other *Node, deepCopy bool) *Node

Copy Will set this node like the one in argument. this node must be of type TypeUndefined

if deepCopy is true we will copy all the children recursively else we will share the children

return the current Node

func (*Node) DebugPrint added in v1.1.0

func (that *Node) DebugPrint(prefix string)

DebugPrint Print a Node as json withindent

func (*Node) DebugProspect added in v1.1.0

func (that *Node) DebugProspect(indentlevel int, indentchar string)

DebugProspect Print all the data the we ve got on a node and all it s children

func (*Node) DelKey added in v1.1.0

func (that *Node) DelKey(key string) *Node

DelKey will remove a key in the map.

return the current Node.

func (*Node) Get added in v1.1.0

func (that *Node) Get() interface{}

Get Return value of a TypeValue as interface{}

func (*Node) GetKeys added in v1.1.0

func (that *Node) GetKeys() []interface{}

GetKeys Return a slice interface that represent the keys to use with the At fonction (Works only on TypeMap and TypeArray)

func (*Node) GetType added in v1.1.0

func (that *Node) GetType() NodeType

GetType Is use to Get the Type of a node

func (*Node) Len added in v1.1.0

func (that *Node) Len() int

Len Return the length of the current Node

if TypeUndefined return 0

if TypeValue return 1

if TypeArray return the size of the array

if TypeMap return the size of the map

func (*Node) Map added in v1.1.0

func (that *Node) Map(key string) *Node

Map Turn this Node to a TypeMap and/or Create a new element for key if necessary and return it

func (*Node) MarshalJSON added in v1.1.0

func (that *Node) MarshalJSON() ([]byte, error)

MarshalJSON Make Node a Marshaler Interface compatible

func (*Node) MustGetBool added in v1.1.0

func (that *Node) MustGetBool() bool

MustGetBool Return value of a TypeValue as bool will panic if cant convert the internal value or if the node is not a TypeValue

func (*Node) MustGetFloat32 added in v1.1.0

func (that *Node) MustGetFloat32() float32

MustGetFloat32 Return value of a TypeValue as float32 will panic if cant convert the internal value or if the node is not a TypeValue

func (*Node) MustGetFloat64 added in v1.1.0

func (that *Node) MustGetFloat64() float64

MustGetFloat64 Return value of a TypeValue as float64 will panic if cant convert the internal value or if the node is not a TypeValue

func (*Node) MustGetInt added in v1.1.0

func (that *Node) MustGetInt() int

MustGetInt Return value of a TypeValue as int will panic if cant convert the internal value or if the node is not a TypeValue

func (*Node) MustGetInt16 added in v1.1.0

func (that *Node) MustGetInt16() int16

MustGetInt16 Return value of a TypeValue as int16 will panic if cant convert the internal value or if the node is not a TypeValue

func (*Node) MustGetInt32 added in v1.1.0

func (that *Node) MustGetInt32() int32

MustGetInt32 Return value of a TypeValue as int32 will panic if cant convert the internal value or if the node is not a TypeValue

func (*Node) MustGetInt64 added in v1.1.0

func (that *Node) MustGetInt64() int64

MustGetInt64 Return value of a TypeValue as int64 will panic if cant convert the internal value or if the node is not a TypeValue

func (*Node) MustGetInt8 added in v1.1.0

func (that *Node) MustGetInt8() int8

MustGetInt8 Return value of a TypeValue as int8 will panic if cant convert the internal value or if the node is not a TypeValue

func (*Node) MustGetString added in v1.1.0

func (that *Node) MustGetString() string

MustGetString Return value of a TypeValue as string will panic if cant convert the internal value or if the node is not a TypeValue

func (*Node) MustGetUint added in v1.1.0

func (that *Node) MustGetUint() uint

MustGetUint Return value of a TypeValue as uint will panic if cant convert the internal value or if the node is not a TypeValue

func (*Node) MustGetUint16 added in v1.1.0

func (that *Node) MustGetUint16() uint16

MustGetUint16 Return value of a TypeValue as uint16 will panic if cant convert the internal value or if the node is not a TypeValue

func (*Node) MustGetUint32 added in v1.1.0

func (that *Node) MustGetUint32() uint32

MustGetUint32 Return value of a TypeValue as uint32 will panic if cant convert the internal value or if the node is not a TypeValue

func (*Node) MustGetUint64 added in v1.1.0

func (that *Node) MustGetUint64() uint64

MustGetUint64 Return value of a TypeValue as uint64 will panic if cant convert the internal value or if the node is not a TypeValue

func (*Node) MustGetUint8 added in v1.1.0

func (that *Node) MustGetUint8() uint8

MustGetUint8 Return value of a TypeValue as uint8 will panic if cant convert the internal value or if the node is not a TypeValue

func (*Node) Print added in v1.1.0

func (that *Node) Print()

Print Print all the data the we ve got on a node and all it s children as a go struct :) (FOR DEV PURPOSE)

func (*Node) SetType added in v1.1.0

func (that *Node) SetType(t NodeType) *Node

SetType Is use to set the Type of a node and return the current Node you are working on

func (*Node) UnmarshalDontExpand added in v1.1.0

func (that *Node) UnmarshalDontExpand(val bool, recurse bool) *Node

UnmarshalDontExpand set or not if Unmarshall will generate anything in that Node and its children

val: will change the expanding rules for this node

- The type wont be change for any type

- Array wont grow

- New keys wont be added to Map

- Values set to nil "*.Val(nil)*" will be turn into the type decide by Json

- It will respect any current mapping and will return errors if needed

recurse: if true, it will set all the children of that Node with val

func (*Node) UnmarshalJSON added in v1.1.0

func (that *Node) UnmarshalJSON(data []byte) error

UnmarshalJSON Make Node a Unmarshaler Interface compatible

func (*Node) Unset added in v1.1.0

func (that *Node) Unset()

Unset Will unset everything in the Node. All the children data will be lost

func (*Node) Val added in v1.1.0

func (that *Node) Val(val interface{})

Val Turn this Node to Value type and/or set that value to val

type NodeType added in v1.1.0

type NodeType uint

NodeType is used to set, check and get the inner type of a Node

const (
	//TypeUndefined is set by default for empty Node
	TypeUndefined NodeType = iota
	//TypeMap is set when a Node is a Map
	TypeMap
	//TypeArray is set when a Node is an Array
	TypeArray
	//TypeValue is set when a Node is a Value Node
	TypeValue
)

func (NodeType) String added in v1.1.0

func (i NodeType) String() string

Jump to

Keyboard shortcuts

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