Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

How to convert json to struct in golang

Shulou Source: shulou.com Published: 2022-06-02 07:45:06 09月20日 Update

这期内容当中小编将会给大家带来有关golang中怎么将json转化成struct,文章内容丰富且以专业的角度为大家分析和叙述,阅读完这篇文章希望大家可以有所收获。

举个例子:

[{ "description" : "An imaginary server config file", "logs" : {"level":"verbose", "dir":"/var/log"}, "host" : "antlr.org", "admin": ["parrt", "tombu"], "aliases": [ ], "Spaces": { }, "keys":[1,2,3,4], "null_": null, "bool_": true, "structs":[{"a":"a","b":"2"}]}]

针对这个json文件可以生成如下数据结构

package Generated

type AutoGenerated []struct { Description string `json:"description"` Logs struct { Level string `json:"level"` Dir string `json:"dir"` } `json:"logs"` Host string `json:"host"` Admin []string `json:"admin"` Aliases []interface{} `json:"aliases"` Spaces struct { } `json:"Spaces"` Keys []float64 `json:"keys"` Null_ interface{} `json:"null_"` Bool_ bool `json:"bool_"` Structs []struct { A string `json:"a"` B string `json:"b"` } `json:"structs"`}

这个轮子的代码我放在

https://github.com/xiazemin/jsonToAll

欢迎体验

如何使用呢

package main

import ( "fmt" "github.com/xiazemin/jsonToAll/file" "github.com/xiazemin/jsonToAll/generator"

"log")

func main() { strOri,strGen:=generator.Gen("./t.json","go") fmt.Println(strOri) log.Println(strGen)

file.PutGoLang("./gen/t.go",strGen) strJsonOri,strJsonGen:=generator.Gen("./t.json","json") fmt.Println(strJsonGen) log.Println(strJsonOri)

file.PutJson("./gen/t.json",strJsonGen)}

上述就是小编为大家分享的golang中怎么将json转化成struct了,如果刚好有类似的疑惑,不妨参照上述分析进行理解。如果想知道更多相关知识,欢迎关注行业资讯频道。

Tags: Content analysis professional small and medium code examples rich in content that is data data structures documents articles more knowledge articles structures industries perspectives information information channels Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Shulou Technology macOS Huawei Shulou Information MySQL