golang如何修改json文件内容的方法示例
作者:CodingCode 时间:2024-04-26 17:32:44
使用一个例子说明golang如何访问和修改json文件;主要分三步:
从文件读入json串
把json串转变成golang对象
遍历或者修改json值
写回文件
假定用户输入json串为:
{
"user": {
"mspid": "admin",
"email": "admin@domain.com"
},
"nodes": [
{
"name": "node1",
"location": "node1.domain.com:8080"
},
{
"name": "node2",
"location": "node2.domain.com:8080"
}
]
}
我们的目标是把node1和node2的location域换掉。
代码如下
import (
"fmt"
"io/ioutil"
"encoding/json"
)
func HandleJson(jsonFile string, outFile string) error {
// Read json buffer from jsonFile
byteValue, err := ioutil.ReadFile(jsonFile)
if err != nil {
return err
}
// We have known the outer json object is a map, so we define result as map.
// otherwise, result could be defined as slice if outer is an array
var result map[string]interface{}
err = json.Unmarshal(byteValue, &result)
if err != nil {
return err
}
// handle peers
nodes:= result["nodes"].([]interface{})
for _, node:= range node{
m := node.(map[string]interface{})
if name, exists := m["name"]; exists {
if name == "node1" {
m["location"] = "new-value1"
} else if name == "node2" {
m["location"] = "new-value2"
}
}
}
// Convert golang object back to byte
byteValue, err = json.Marshal(result)
if err != nil {
return err
}
// Write back to file
err = ioutil.WriteFile(outFile, byteValue, 0644)
return err
}
这个地方主要用的是golang的interface{}数据类型,然后把interface{}转换成真正的数据类型。
这个函数可以扩充成动态的解析任何类型,只要把所有的类型全部定义成interface{},然后使用动态类型检测就可以知道每一个具体元素的类型了,最终达到类型jq的功能,访问和修改json文件。
var x interface{} = ...
switch x.(type) {
case nil:
fmt.Println("x is nil")
case int:
fmt.Println("x is int")
case bool :
fmt.Println("x is bool")
case string:
fmt.Println("x is string")
case []interface{}:
fmt.Println("x is slice")
case map[string]interface{}:
fmt.Println("x is map")
default:
fmt.Println("type unknown")
}
}
PS:据说json-iteator 是目前golang中对json格式数据处理最快的包(比官方json包快6倍),好像是滴滴团队开源的,使用起来也非常方便,有兴趣的可以学习学习,下面我们看看官方的示例代码,使用起来也是很方便
package main
import "github.com/json-iterator/go"
type User struct {
Name string
Age int8
}
func main() {
user := User{
Name: "tanggu",
Age: 18,
}
var jsoniter = jsoniter.ConfigCompatibleWithStandardLibrary
// 序列化
data, err := jsoniter.Marshal(&user)
if err != nil {
log.Fatal(err)
}
fmt.Println(string(data))
// 反序列化
var people User
err = jsoniter.Unmarshal(data, &people)
if err != nil {
log.Fatal(err)
}
fmt.Println(people)
}
来源:https://studygolang.com/articles/15201
标签:golang,json
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
网站构成的基本元素—网页布局
2008-01-04 09:49:00
用Javascript正则表达式验证Email地址
2009-12-09 15:56:00
儿童学习python的一些小技巧
2021-10-14 05:09:40
python中os模块和sys模块的使用详解
2021-08-29 21:42:35
![](https://img.aspxhome.com/file/2023/3/97403_0s.png)
SQL server 表数据改变触发发送邮件的方法
2024-01-23 02:15:48
javascript FAQ函数(提问+回复)
2024-04-19 09:55:54
![](https://img.aspxhome.com/file/2023/6/136006_0s.gif)
Oracle 11g数据库安装与卸载的方法图解
2024-01-22 19:54:15
![](https://img.aspxhome.com/file/2023/7/67527_0s.gif)
mysql调优的几种方式小结
2024-01-25 22:24:41
Python Selenium自动化获取页面信息的方法
2023-08-22 18:29:31
正则表达式学习笔记
2008-04-15 07:44:00
MySQL中对于not in和minus使用的优化
2024-01-17 04:17:20
Python开发常用的一些开源Package分享
2022-12-10 22:00:11
深入理解Pytorch中的torch. matmul()
2023-06-03 05:29:18
![](https://img.aspxhome.com/file/2023/5/107175_0s.jpg)
python函数enumerate,operator和Counter使用技巧实例小结
2022-08-09 07:02:32
python读写ini文件示例(python读写文件)
2023-06-21 03:10:14
TensorFlow人工智能学习按索引取数据及维度变换详解
2024-01-04 13:18:55
![](https://img.aspxhome.com/file/2023/4/67274_0s.png)
Python判断telnet通不通的实例
2023-07-27 14:56:08
服务器不支持 MySql 数据库的解决方法
2024-01-15 11:44:57
Python实现端口检测的方法
2022-02-01 21:21:02
![](https://img.aspxhome.com/file/2023/0/101720_0s.png)
Python assert关键字原理及实例解析
2022-11-12 09:24:10