SoFunction
Updated on 2025-03-01

Example of method of parsing json data using Golang

This article mainly introduces to you the relevant content about Golang's analysis of json data. It is shared for your reference and learning. I won't say much below. Let's take a look at the detailed introduction together:

Use Golang to parse json data. This json format is an array of objects. The official documentation 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 := (jsonBlob, &animals) 
if err != nil { 
 ("error:", err) 
} 
("%+v", animals)

It can parse objects of json data into the corresponding structure.

If it is a one-dimensional array, the form of key-value pairs is: {"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
 (jsonData, &a)
 ("%+v\n", a)
}

The json in the form of visible key-value pairs can be mapped into a map, orinterface{} .

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
 (jsonData, &a)
 ("%+v\n", a)
}

It can be seen that only the form of values ​​can be mapped into a slice.

Regarding json data parsing, the types are explained in 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

Simulate PHPjson_decode($jsonString, true)function

However, depending on this situation, in PHP, ifjson_decode(‘[“a”,”b”,”c”,”d”,”e”]', true) This second parameter is true parsing json, which can be parsed into the form of an object with key-value pairs:

[
 0=>"a",
 1=>"b",
 2=>"c",
 3=>"d",
 4=>"e"
]

How to do this kind of Golang?

func main() {
 jsonData := []byte(`["a","b","c","d","e"]`)
 var a []string
 (jsonData, &a)
 
 newData := make(map[int]string)
 for k, v := range a {
 newData[k] = v
 }
 
 ("%+v\n", newData)
}

There should be no built-in functions, so just implement it manually.

Summarize

The above is the entire content of this article. I hope that the content of this article will be of some help to everyone’s learning or using Go. If you have any questions, you can leave a message to communicate. Thank you for your support.