Golang:如何在Go中将JSON转换为Map
Golang json是最常用的软件包之一。 JSON(JavaScript对象表示法)为开发人员解析一天的活动。开发人员解析的大多数API都是JSON。在这里,我们将看到如何将JSON对象解析为Map。
如何在Golang中将JSON转换为Map
我们将看到如何使用Golang接口解析JSON对象和数组。当数据非结构化时,它减少了创建结构的开销,并且我们可以解析数据并从JSON获取所需的值。
让我们看下面的例子。
// hello.go package main import ( "encoding/json" "fmt" "reflect" ) func main() { //Simple Employee JSON object which we will parse coronaVirusJSON := `{ "name" : "covid-11", "country" : "China", "city" : "Wuhan", "reason" : "Non vedge Food" }` // Declared an empty map interface var result map[string]interface{} // Unmarshal or Decode the JSON to the interface. json.Unmarshal([]byte(coronaVirusJSON), &result) // Print the data type of result variable fmt.Println(reflect.TypeOf(result)) // Reading each value by its key fmt.Println("Name :", result["name"], "nCountry :", result["country"], "nCity :", result["city"], "nReason :", result["reason"]) }
输出量
go run hello.go map[string]interface {} Name : covid-11 Country : China City : Wuhan Reason : Non vedge Food
说明
首先,我们导入了“ encoding / json”,“ fmt”,“ reflect”包。
然后在main()中,我定义了一个简单的JSON对象,称为coronaVirusJSON对象。
它具有四个属性,现在我们需要转换该json对象,以在控制台中一对一地映射和显示其键值。
为此,在下一步中,我声明了带有空接口的字符串映射,该接口将保存已解析的json的值。
然后,我已经使用json.Unmarshal()函数通过将json字符串转换为字节到映射中来解组json字符串。 Unmarshal解析JSON编码的数据,并将结果存储在接口指向的值中。如果接口为nil或不是指针,则Unmarshal返回InvalidUnmarshalError。 Unmarshal()函数使用Marshal使用的编码的倒数,分配映射,切片和指针。
在最后一步中,由于结果是一个映射变量,因此我们已经通过键打印了值,并且可以通过键访问它。