An example of a method to parse json data using Golang
- 2020-06-12 09:17:09
- OfStack
This paper is mainly about the Golang analysis of json data related content, to share for your reference and learning, the following is not enough to say, let's have a look at the detailed introduction:
Parse json data using Golang, the json format is an array of objects, the official document has an example:
var jsonBlob = []byte(`[
{"Name": "Platypus", "Order": "Monotremata"},
{"Name": "Quoll", "Order": "Dasyuromorphia"}
]`)
type Animal struct {
Name string
Order string
}
var animals []Animal
err := json.Unmarshal(jsonBlob, &animals)
if err != nil {
fmt.Println("error:", err)
}
fmt.Printf("%+v", animals)
It can parse the object of json data into the corresponding structure.
If it is a one dimensional array, with key-value pairs, such as: {" A ":3," B ":3," C ":5," D ":5}, the code is as follows:
func main() {
jsonData := []byte(`{"A":3,"B":3,"C":5,"D":5}`)
var a map[string]int
json.Unmarshal(jsonData, &a)
fmt.Printf("%+v\n", a)
}
You can see that json in key-value pair form can be mapped to map, or
interface{}
.
If it is a value-only form such as [" a ", "b", "c", "d", "e"], the code is as follows:
func main() {
jsonData := []byte(`["a","b","c","d","e"]`)
var a []string
json.Unmarshal(jsonData, &a)
fmt.Printf("%+v\n", a)
}
You can see that only value forms can be mapped to 1 slice.
About json data parsing For types, it is explained in the function comments:
To unmarshal JSON into an interface value,Unmarshal stores one of these in the interface value:
bool, for JSON booleans
float64, for JSON numbers
string, for JSON strings
[]interface{}, for JSON arrays
map[string]interface{}, for JSON objects
nil for JSON null
Simulation of the PHP
json_decode($jsonString, true)
function
But, in this case, in PHP, if you use
json_decode(‘[“a”,”b”,”c”,”d”,”e”]', true)
The second parameter is true's parse json, which can be resolved into the form of an object with key-value pairs:
[
0=>"a",
1=>"b",
2=>"c",
3=>"d",
4=>"e"
]
How does this Golang do it?
func main() {
jsonData := []byte(`["a","b","c","d","e"]`)
var a []string
json.Unmarshal(jsonData, &a)
newData := make(map[int]string)
for k, v := range a {
newData[k] = v
}
fmt.Printf("%+v\n", newData)
}
There should be no built-in functions, so implement them manually.
conclusion