利用Golang解析json数据的方法示例
作者:小谈 时间:2024-04-27 15:36:04
本文主要给大家介绍的是关于Golang解析json数据的相关内容,分享出来供大家参考学习,下面话不多说了,来一起看看详细的介绍:
使用 Golang 解析 json 数据,这种 json 格式是对象的数组,官方文档有一个示例:
var jsonBlob = []byte(`[
{"Name": "Platypus", "Order": "Monotremata"},
{"Name": "Quoll", "Order": "Dasyuromorphia"}
]`)
type Animal struct {
Name string
Order string
}
var animals []Animal
err := json.Unmarshal(jsonBlob, &animals)
if err != nil {
fmt.Println("error:", err)
}
fmt.Printf("%+v", animals)
它可以把 json 数据的对象解析到对应的结构体中。
如果是一维数组,带键值对的形式,如:{“A”:3,”B”:3,”C”:5,”D”:5},代码如下:
func main() {
jsonData := []byte(`{"A":3,"B":3,"C":5,"D":5}`)
var a map[string]int
json.Unmarshal(jsonData, &a)
fmt.Printf("%+v\n", a)
}
可见键值对形式的 json 可以映射到 map 中,或者 interface{}
.
如果是只有值的形式,如:[“a”,”b”,”c”,”d”,”e”],代码如下:
func main() {
jsonData := []byte(`["a","b","c","d","e"]`)
var a []string
json.Unmarshal(jsonData, &a)
fmt.Printf("%+v\n", a)
}
可见只有值的形式可以映射到一个 slice 中。
关于 json 数据解析对于类型,在函数注释中都已有说明:
To unmarshal JSON into an interface value,Unmarshal stores one of these in the interface value:
bool, for JSON booleans
float64, for JSON numbers
string, for JSON strings
[]interface{}, for JSON arrays
map[string]interface{}, for JSON objects
nil for JSON null
模拟 PHP 的 json_decode($jsonString, true)
函数
但是,看这种情况,在 PHP 中,如果用 json_decode(‘[“a”,”b”,”c”,”d”,”e”]', true)
这种第二个参数是 true 的解析 json,可以解析为带键值对的对象的形式:
[
0=>"a",
1=>"b",
2=>"c",
3=>"d",
4=>"e"
]
这种 Golang 怎么做到呢?
func main() {
jsonData := []byte(`["a","b","c","d","e"]`)
var a []string
json.Unmarshal(jsonData, &a)
newData := make(map[int]string)
for k, v := range a {
newData[k] = v
}
fmt.Printf("%+v\n", newData)
}
应该没有内置函数,那就这样手动实现吧。
来源:https://blog.tanteng.me/2017/07/golang-decode-json/
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
matplotlib图例legend语法及设置的方法
![](https://img.aspxhome.com/file/2023/6/78516_0s.png)
Git文件常用操作总结及拓展
![](https://img.aspxhome.com/file/2023/2/131832_0s.png)
Python日志logging模块功能与用法详解
![](https://img.aspxhome.com/file/2023/1/107991_0s.png)
Python趣味挑战之给幼儿园弟弟生成1000道算术题
![](https://img.aspxhome.com/file/2023/0/127660_0s.png)
python人物视频背景替换实现虚拟空间穿梭
![](https://img.aspxhome.com/file/2023/0/82690_0s.png)
分析用Python脚本关闭文件操作的机制
js断点调试经验分享
![](https://img.aspxhome.com/file/2023/7/55897_0s.png)
python切片作为占位符使用实例讲解
MySQL在Windows中net start mysql 启动MySQL服务报错 发生系统错误解决方案
![](https://img.aspxhome.com/file/2023/2/96502_0s.jpg)
Go语言kylin任务自动化实例详解
![](https://img.aspxhome.com/file/2023/6/127436_0s.jpg)
您是否记得关闭所有的XHTML元素
使用Python3编写抓取网页和只抓网页图片的脚本
Python 如何用一行代码实现for循环初始化数组
Python办公自动化批量处理文件实现示例
![](https://img.aspxhome.com/file/2023/6/112096_0s.png)
使用python检测手机QQ在线状态的脚本代码
python openCV实现摄像头获取人脸图片
![](https://img.aspxhome.com/file/2023/5/68475_0s.jpg)
RS.GETROWS使用详解
asp使用正则自动解析图片地址并保存
![](https://img.aspxhome.com/file/UploadPic/up/2007081711544653.jpg)
jupyter notebook 恢复误删单元格或者历史代码的实现
![](https://img.aspxhome.com/file/2023/2/87562_0s.jpg)
教你如何使Python爬取酷我在线音乐
![](https://img.aspxhome.com/file/2023/6/134716_0s.jpg)