jsonutil

package
v0.0.0-...-3f59448 Latest Latest
Warning

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

Go to latest
Published: Sep 14, 2016 License: Apache-2.0 Imports: 3 Imported by: 0

Documentation

Overview

Package jsonutil contains various utilities for dealing with json data.

Package jsonutil contains various utilities for dealing with json data.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Indent

func Indent(jsonStr string) string

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

func Marshal(obj interface{}) (result string, err error)

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

func UnmarshalFile(filePath string, dest interface{}) (err error)

UnmarshalFile reads the content of a file then Unmarshals the content to an object.

Types

This section is empty.

Jump to

Keyboard shortcuts

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