golang 字符串转换为 json数据
本文介绍了golang 字符串转换为 json数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
问 题
例如 "{"src_ip": "localhost"}" 这样的字符串如何转换成json数据如{"src_ip":"localhost"}
解决方案
给你个golang操作json的例子,这里用的是官方的json包,很多时候我们应用的是第三方的包,比如说"go-simplejson"或者其他的第三方包。
package main
import (
"encoding/json"
"fmt"
"os"
)
type ConfigStruct struct {
Host string `json:"host"`
Port int `json:"port"`
AnalyticsFile string `json:"analytics_file"`
StaticFileVersion int `json:"static_file_version"`
StaticDir string `json:"static_dir"`
TemplatesDir string `json:"templates_dir"`
SerTcpSocketHost string `json:"serTcpSocketHost"`
SerTcpSocketPort int `json:"serTcpSocketPort"`
Fruits []string `json:"fruits"`
}
type Other struct {
SerTcpSocketHost string `json:"serTcpSocketHost"`
SerTcpSocketPort int `json:"serTcpSocketPort"`
Fruits []string `json:"fruits"`
}
func main() {
jsonStr := `{"host": "http://localhost:9090","port": 9090,"analytics_file": "","static_file_version": 1,"static_dir": "E:/Project/goTest/src/","templates_dir": "E:/Project/goTest/src/templates/","serTcpSocketHost": ":12340","serTcpSocketPort": 12340,"fruits": ["apple", "peach"]}`
//json str 转map
var dat map[string]interface{}
if err := json.Unmarshal([]byte(jsonStr), &dat); err == nil {
fmt.Println("==============json str 转map=======================")
fmt.Println(dat)
fmt.Println(dat["host"])
}
//json str 转struct
var config ConfigStruct
if err := json.Unmarshal([]byte(jsonStr), &config); err == nil {
fmt.Println("================json str 转struct==")
fmt.Println(config)
fmt.Println(config.Host)
}
//json str 转struct(部份字段)
var part Other
if err := json.Unmarshal([]byte(jsonStr), &part); err == nil {
fmt.Println("================json str 转struct==")
fmt.Println(part)
fmt.Println(part.SerTcpSocketPort)
}
//struct 到json str
if b, err := json.Marshal(config); err == nil {
fmt.Println("================struct 到json str==")
fmt.Println(string(b))
}
//map 到json str
fmt.Println("================map 到json str=====================")
enc := json.NewEncoder(os.Stdout)
enc.Encode(dat)
//array 到 json str
arr := []string{"hello", "apple", "python", "golang", "base", "peach", "pear"}
lang, err := json.Marshal(arr)
if err == nil {
fmt.Println("================array 到 json str==")
fmt.Println(string(lang))
}
//json 到 []string
var wo []string
if err := json.Unmarshal(lang, &wo); err == nil {
fmt.Println("================json 到 []string==")
fmt.Println(wo)
}
}
这篇关于golang 字符串转换为 json数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文