jsonutil

package
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: May 15, 2025 License: Apache-2.0 Imports: 4 Imported by: 0

Documentation

Overview

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, error)

Indent indents a json string.

Example
type Road struct {
	Name   string
	Number int
}

roads := []Road{
	{Name: "Diamond Fork", Number: 29},
	{Name: "Sheep Creek", Number: 51},
}

b, err := Marshal(roads)
if err != nil {
	log.Fatal(err)
}

out, err := Indent(b)
if err != nil {
	log.Fatal(err)
}

fmt.Println(out)
Output:
[
  {
    "Name": "Diamond Fork",
    "Number": 29
  },
  {
    "Name": "Sheep Creek",
    "Number": 51
  }
]

func Marshal

func Marshal(obj any) (string, 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 MarshalIndent

func MarshalIndent(obj any) (string, error)

MarshalIndent is like Marshal but applies Indent to format the output. Returns empty string if marshal fails.

func Remarshal

func Remarshal(obj any, remarshalledObj any) 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]any 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 Unmarshal

func Unmarshal(jsonContent string, dest any) error

Unmarshal unmarshals the content in string format to an object.

func UnmarshalFile

func UnmarshalFile(filePath string, dest any) 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