Golang 如何解析JSON

Golang 如何解析JSON

Golang提供多个API来处理JSON,包括使用内置和自定义数据类型进行JSON的转换,使用encoding/json包。要解析JSON,我们使用encoding/json包中的Unmarshal()函数将数据从JSON解包或解码为结构体。

语法: func Unmarshal(data []byte, v interface{}) error

Unmarshal解析JSON编码数据并将结果存储在指向v的值中。

注意: 如果v为nil或不是指针,则Unmarshal返回InvalidUnmarshalError。

示例1:

//Golang演示程序说明
//将JSON解析为结构体
package main

import (
    "encoding/json"
    "fmt"
)

//声明结构体
type Country struct {

    //定义结构体变量
    Name      string
    Capital   string
    Continent string
}

//主程序
func main() {

    //定义一个结构体实例
    var country1 Country

    //要解码的JSON格式数据
    Data := []byte(`{
        "Name": "India",
        "Capital": "New Delhi",
        "Continent": "Asia"
    }`)

    //从JSON格式中解码country1结构体
    err := json.Unmarshal(Data, &country1;)

    if err != nil {

        //如果错误不为空,则打印错误
        fmt.Println(err)
    }

    //打印解码数据的详细信息
    fmt.Println("结构体为:", country1)
    fmt.Printf("%s的首都是%s,位于%s。\n", country1.Name,
        country1.Capital, country1.Continent)
} 
Go

输出:

结构体为:{India New Delhi Asia}
印度的首都是新德里,位于亚洲。
Go

示例2:

// Golang演示程序说明
//解析JSON到数组的概念
package main

import (
    "encoding/json"
    "fmt"
)

//声明结构体
type Country struct {

    //定义结构体变量
    Name      string
    Capital   string
    Continent string
}

//主程序
func main() {

    //定义一个结构体实例
    var country []Country

    //要解码的JSON数组
    //根据golang的数组进行解码
    Data := []byte(`
    [
        {"Name": "Japan", "Capital": "Tokyo", "Continent": "Asia"},
        {"Name": "Germany", "Capital": "Berlin", "Continent": "Europe"},
        {"Name": "Greece", "Capital": "Athens", "Continent": "Europe"},
        {"Name": "Israel", "Capital": "Jerusalem", "Continent": "Asia"}
    ]`)

    //将JSON数组解码为国家数组
    err := json.Unmarshal(Data, &country;)

    if err != nil {

        //如果错误不为空,则打印错误
        fmt.Println(err)
    }

    //打印解码后的数组的每个值
    for i := range country {
        fmt.Println(country[i].Name + " - " + country[i].Capital +
            " - " + country[i].Continent)
    }
} 
Go

输出:

日本 - 东京 - 亚洲
德国 - 柏林 - 欧洲
希腊 - 雅典 - 欧洲
以色列 - 耶路撒冷 - 亚洲
Go

解析JSON为map

在某些情况下,我们不知道JSON的结构,因此无法定义用于解码数据的结构体。为此,我们可以创建一个map[string]interface{}

示例1:

//演示将JSON解析为映射的程序
package main
 
import (
    "encoding/json"
    "fmt"
)
 
func main() {
 
    //声明一个映射
    //键为字符串类型,值为类型接口{},可存储任何类型的值
    var person map[string]interface{}
     
    //要解码的JSON数据
    jsonData := `{
        "name":"Jake",
        "country":"US",
        "state":"Connecticut"
    }`
     
    //将JSON数据解码并存储在person映射中
    err := json.Unmarshal([]byte(jsonData), &person)
     
    //检查错误是否为nil
    if err != nil {
     
        //如果不是nil则打印错误
        fmt.Println("Error while decoding the data", err.Error())
    }
 
    //打印解码数据的详细信息
    fmt.Println("The name of the person is", person["name"], "and he lives in", person["country"])
 
} 
Go

输出:

The name of the person is Jake and he lives in US
Go

示例2:

//演示将JSON解析为数组的程序
package main
 
import (
    "encoding/json"
    "fmt"
)
 
func main() {
 
    //定义一个人的数组
    var persons []map[string]interface{}
 
    //要解码为golang数组的JSON数组
    jsonData := `[{
        "name":"Jake",
        "country":"US",
        "state":"Connecticut"
    },
    {
        "name":"Jacob",
        "country":"US",
        "state":"NewYork"
    },
    {
        "name":"James",
        "country":"US",
        "state":"WashingtonDC"
    }
    ]`
 
    //将JSON数组解码为persons数组
    err := json.Unmarshal([]byte(jsonData), &persons)
 
    if err != nil {
        fmt.Println("Error while decoding the data", err.Error())
    }
 
    //逐个打印解码数组的值
    for index, person := range persons {
 
        fmt.Println("Person:", index+1, "Name:", person["name"], "Country:", person["country"], "State:", person["state"])
    }
 
} 
Go

输出:

Person: 1 Name: Jake Country: US State: Connecticut
Person: 2 Name: Jacob Country: US State: NewYork
Person: 3 Name: James Country: US State: WashingtonDC
Go

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程

登录

注册