内容简介:golang如何修改json文件内容使用一个例子说明golang如何访问和修改json文件;主要分三步:假定用户输入json串为:
golang如何修改json文件内容
使用一个例子说明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")
}
}
以上所述就是小编给大家介绍的《golang如何修改json文件内容》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
Algorithms + Data Structures = Programs
Niklaus Wirth / Prentice Hall / 1975-11-11 / GBP 84.95
It might seem completely dated with all its examples written in the now outmoded Pascal programming language (well, unless you are one of those Delphi zealot trying to resist to the Java/.NET dominanc......一起来看看 《Algorithms + Data Structures = Programs》 这本书的介绍吧!