go2struct

package module
v0.1.2 Latest Latest
Warning

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

Go to latest
Published: Dec 16, 2021 License: Apache-2.0 Imports: 5 Imported by: 0

README

go2struct

Convert arbitrary formats to Go Struct (including json, toml, yaml, etc.)

Installation

Run the following command under your project:

go get -u github.com/NICEXAI/go2struct

Feature
  • Map to struct
  • JSON to struct
  • YAML to struct
  • TOML to struct
Example
package main

import (
	"encoding/json"
	"fmt"
	"github.com/NICEXAI/go2struct"
)

type Message struct {
	Code    int  `json:"code"`
	Success bool `json:"success"`
	Msg     struct {
		Content string
	} `json:"msg"`
}

func main() {
	var options map[string]interface{}

	message := Message{
		Code: 200,
		Msg:  struct{ Content string }{Content: "Hello"},
	}

	bData, err := json.Marshal(message)
	if err != nil {
		fmt.Printf("json marshal failed, error: %v", err)
		return
	}
	_ = json.Unmarshal(bData, &options)

	//map to struct
	structTxt := go2struct.Map2Struct("message", options)

	fmt.Printf("map to struct success, result: \n%s", structTxt)

	// json to struct
	jsonTemp := `
	{
	 "code": 200,
	 "success": true,
	 "msg": {
		"content": "Hello"
	 }
	}
	`

	res, err := go2struct.JSON2Struct("message", []byte(jsonTemp))
	if err != nil {
		fmt.Printf("json to struct failed, error: \n%v", err)
		return
	}
	fmt.Printf("json to struct success, result: \n%s", res)

	// yaml to struct
	temp := `
code: 200
success: true
msg:
 content: Hello
`

	res, err = go2struct.YAML2Struct("message", []byte(temp))
	if err != nil {
		fmt.Printf("yaml to struct failed, error: \n%v", err)
		return
	}
	fmt.Printf("yaml to struct success, result: \n%s", res)
}

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func JSON2Struct

func JSON2Struct(name string, data []byte, args ...string) ([]byte, error)

JSON2Struct convert json to struct

func Map2Struct

func Map2Struct(name string, m map[string]interface{}, args ...string) []byte

Map2Struct convert map to struct

func YAML2Struct

func YAML2Struct(name string, data []byte, args ...string) ([]byte, error)

YAML2Struct convert yaml to struct

Types

This section is empty.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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