golang如何修改json文件內(nèi)容的方法示例
使用一個(gè)例子說(shuō)明golang如何訪問(wèn)和修改json文件;主要分三步:
- 從文件讀入json串
- 把json串轉(zhuǎn)變成golang對(duì)象
- 遍歷或者修改json值
- 寫回文件
假定用戶輸入json串為:
{ "user": { "mspid": "admin", "email": "admin@domain.com" }, "nodes": [ { "name": "node1", "location": "node1.domain.com:8080" }, { "name": "node2", "location": "node2.domain.com:8080" } ] }
我們的目標(biāo)是把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 }
這個(gè)地方主要用的是golang的interface{}數(shù)據(jù)類型,然后把interface{}轉(zhuǎn)換成真正的數(shù)據(jù)類型。
這個(gè)函數(shù)可以擴(kuò)充成動(dòng)態(tài)的解析任何類型,只要把所有的類型全部定義成interface{},然后使用動(dòng)態(tài)類型檢測(cè)就可以知道每一個(gè)具體元素的類型了,最終達(dá)到類型jq的功能,訪問(wèn)和修改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:據(jù)說(shuō)json-iteator 是目前golang中對(duì)json格式數(shù)據(jù)處理最快的包(比官方j(luò)son包快6倍),好像是滴滴團(tuán)隊(duì)開(kāi)源的,使用起來(lái)也非常方便,有興趣的可以學(xué)習(xí)學(xué)習(xí),下面我們看看官方的示例代碼,使用起來(lái)也是很方便
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) }
以上就是這篇文章的全部?jī)?nèi)容了,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,如果有疑問(wèn)大家可以留言交流,謝謝大家對(duì)腳本之家的支持。
- golang使用json格式實(shí)現(xiàn)增刪查改的實(shí)現(xiàn)示例
- golang json.Marshal 特殊html字符被轉(zhuǎn)義的解決方法
- golang結(jié)構(gòu)體與json格式串實(shí)例代碼
- Golang JSON的進(jìn)階用法實(shí)例講解
- golang如何自定義json序列化應(yīng)用詳解
- golang json性能分析詳解
- golang中json反序列化可能遇到的問(wèn)題
- Golang map如何生成有序的json數(shù)據(jù)詳解
- 利用Golang解析json數(shù)據(jù)的方法示例
- Golang中使用JSON的一些小技巧分享
- golang實(shí)現(xiàn)sql結(jié)果集以json格式輸出的方法
- Golang 如何解析和生成json
相關(guān)文章
Go語(yǔ)言防范SQL注入CSRF及XSS攻擊實(shí)例探究
在本文中,我們將會(huì)介紹幾種最常見(jiàn)的攻擊類型,并且介紹如何使用Golang來(lái)防范這些攻擊,本文會(huì)涉及XSS攻擊、CSRF攻擊、SQL注入等,如果你想學(xué)習(xí)Golang和網(wǎng)絡(luò)安全的相關(guān)知識(shí),那么這篇文章會(huì)是一個(gè)很好的開(kāi)始2024-01-01goland 實(shí)現(xiàn)自動(dòng)格式化代碼
這篇文章主要介紹了goland 實(shí)現(xiàn)自動(dòng)格式化代碼的操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2021-04-04詳解Golang中g(shù)omock的使用場(chǎng)景和方法
gomock是Go編程語(yǔ)言的模擬框架, 它與Go的內(nèi)置測(cè)試包很好地集成在一起,但也可以在其他上下文中使用,本文主要介紹了gomock的使用場(chǎng)景和方法,感興趣的可以了解下2024-10-10golang中sync.Mutex的實(shí)現(xiàn)方法
本文主要介紹了golang中sync.Mutex的實(shí)現(xiàn)方法,mutex?主要有兩個(gè)?method:?Lock()?和?Unlock(),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2022-04-04GO將mysql?中?decimal?數(shù)據(jù)類型映射到?protobuf的操作方法
這篇文章主要介紹了go如何優(yōu)雅地將?mysql?中?decimal?數(shù)據(jù)類型映射到?protobuf,本文主要展示一下在 protobuf中 float與double的一個(gè)區(qū)別,結(jié)合實(shí)例代碼給大家介紹的非常詳細(xì),需要的朋友可以參考下2022-09-09Go語(yǔ)言中使用 buffered channel 實(shí)現(xiàn)線程安全的 pool
這篇文章主要介紹了Go語(yǔ)言中使用 buffered channel 實(shí)現(xiàn)線程安全的 pool,因?yàn)镚o語(yǔ)言自帶的sync.Pool并不是很好用,所以自己實(shí)現(xiàn)了一線程安全的 pool,需要的朋友可以參考下2014-10-10Go?web中cookie值安全securecookie庫(kù)使用原理
這篇文章主要為大家介紹了Go?web中cookie值安全securecookie庫(kù)使用及實(shí)現(xiàn)原理詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-11-11