golang如何修改json檔案內容
golang如何修改json檔案內容
使用一個例子說明golang如何訪問和修改json檔案;主要分三步:
- 從檔案讀入json串
- 把json串轉變成golang物件
- 遍歷或者修改json值
- 寫回檔案
假定使用者輸入json串為:
{ "user": { "mspid": "admin", "email": "[email protected]" }, "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 defineresult 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") } }