Documentation ¶
Overview ¶
Package jsonutil contains various utilities for dealing with json data.
Package jsonutil contains various utilities for dealing with json data.
Index ¶
- func Indent(jsonStr string) string
- func Marshal(obj interface{}) (result string, err error)
- func MarshalIndent(obj interface{}) (result string, err error)
- func Remarshal(obj interface{}, remarshalledObj interface{}) (err error)
- func Unmarshal(jsonContent string, dest interface{}) (err error)
- func UnmarshalFile(filePath string, dest interface{}) (err error)
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func Indent ¶
Indent indents a json string.
Example ¶
type Road struct { Name string Number int } roads := []Road{ {"Diamond Fork", 29}, {"Sheep Creek", 51}, } b, err := Marshal(roads) if err != nil { log.Fatal(err) } out := Indent(b) fmt.Println(out)
Output: [ { "Name": "Diamond Fork", "Number": 29 }, { "Name": "Sheep Creek", "Number": 51 } ]
func Marshal ¶
Marshal marshals an object to a json string. Returns empty string if marshal fails.
Example ¶
type ColorGroup struct { ID int Name string Colors []string } group := ColorGroup{ ID: 1, Name: "Reds", Colors: []string{"Crimson", "Red", "Ruby", "Maroon"}, } b, err := Marshal(group) if err != nil { fmt.Println("error:", err) } fmt.Println(b)
Output: {"ID":1,"Name":"Reds","Colors":["Crimson","Red","Ruby","Maroon"]}
func MarshalIndent ¶
MarshalIndent is like Marshal but applies Indent to format the output. Returns empty string if marshal fails
func Remarshal ¶
func Remarshal(obj interface{}, remarshalledObj interface{}) (err error)
Remarshal marshals an object to Json then parses it back to another object. This is useful for example when we want to go from map[string]interface{} to a more specific struct type or if we want a deep copy of the object.
Example ¶
type ColorGroup struct { ID int Name string Colors []string } group := ColorGroup{ ID: 1, Name: "Reds", Colors: []string{"Crimson", "Red", "Ruby", "Maroon"}, } var newGroup ColorGroup err := Remarshal(group, &newGroup) if err != nil { fmt.Println("error:", err) } out, err := Marshal(newGroup) if err != nil { fmt.Println("error:", err) } fmt.Println(out)
Output: {"ID":1,"Name":"Reds","Colors":["Crimson","Red","Ruby","Maroon"]}
func UnmarshalFile ¶
UnmarshalFile reads the content of a file then Unmarshals the content to an object.
Types ¶
This section is empty.