Use an example to illustrate how golang accesses and modifys json files; it is mainly divided into three steps:
- Reading into a json string from a file
- Convert json string into golang object
- Traversal or modify json value
- Write back to file
Assume that the user input json string is:
{ "user": { "mspid": "admin", "email": "admin@" }, "nodes": [ { "name": "node1", "location": ":8080" }, { "name": "node2", "location": ":8080" } ] }
Our goal is to replace the location fields of node1 and node2.
The code is as follows
import ( "fmt" "io/ioutil" "encoding/json" ) func HandleJson(jsonFile string, outFile string) error { // Read json buffer from jsonFile byteValue, err := (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 = (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 = (result) if err != nil { return err } // Write back to file err = (outFile, byteValue, 0644) return err }
This place mainly uses golang's interface{} data type, and then converts interface{} into a real data type.
This function can be expanded to dynamically parse any type. Just define all types as interface{}, and then use dynamic type detection to know the type of each specific element, and finally achieve the function of type jq, access and modify the json file.
var x interface{} = ... switch x.(type) { case nil: ("x is nil") case int: ("x is int") case bool : ("x is bool") case string: ("x is string") case []interface{}: ("x is slice") case map[string]interface{}: ("x is map") default: ("type unknown") } }
PS:It is said thatjson-iteator It is currently the fastest package for json format data processing in golang (6 times faster than the official json package). It seems to be open source by Didi team and is very convenient to use. If you are interested, you can learn. Let’s take a look at the official sample code below, which is also very convenient to use.
package main import "/json-iterator/go" type User struct { Name string Age int8 } func main() { user := User{ Name: "tanggu", Age: 18, } var jsoniter = // Serialization data, err := (&user) if err != nil { (err) } (string(data)) // Deserialization var people User err = (data, &people) if err != nil { (err) } (people) }
The above is the entire content of this article. I hope that the content of this article has certain reference value for everyone's study or work. If you have any questions, you can leave a message to communicate. Thank you for your support.