Golang 解析JSON 篇 - 知乎

不多说废话,老规矩上代码,看注释。

所用到的库:

os : 处理命令行参数

io/ioutil: 读取文件

bufio: 读取文件,按行读取

package main

/*
    JSON 数据解析
        注意:struct 类型数据 命名时 首字母大写,如果不大写会出现滞空,看不见变量后的数据
*/

import (
    "bufio"
    "encoding/json"
    "fmt"
    "io/ioutil"
    "os"
)

// 第二层 JSON 的 struct 创建
type Hello struct {
    CubeType string
    High     int
    Width    int
    Long     int
}

// 第一层 JSON 的 struct 创建
type Study struct {
    Name      string
    Age       int
    Skill     []string
    SkillType map[string]string
    // 在 A struct 中使用 B struct 就需要指定 B 的内存地址
    Cube *Hello
}

// 创建一个错误处理函数,避免过多的 if err != nil{} 出现
func dropErr(e error) {
    if e != nil {
        panic(e)
    }
}

func main() {
    fmt.Println("Hello,today we will study Golang read JSON data")

    // 获取 参数,请传入一个文件路径
    filePath := os.Args[1]
    fmt.Printf("The file path is :%s\n", filePath)

    // ioutil 方式读取,会一次性读取整个文件,在对大文件处理时会有内存压力
    fileData, err := ioutil.ReadFile(filePath)
    dropErr(err)
    fmt.Println(string(fileData))

    // bufio 读取
    f, err := os.Open(filePath)
    dropErr(err)
    bio := bufio.NewReader(f)
    // ReadLine() 方法一次尝试读取一行,如果过默认缓存值就会报错。默认遇见'\n'换行符会返回值。isPrefix 在查找到行尾标记后返回 false
    bfRead, isPrefix, err := bio.ReadLine()
    dropErr(err)
    fmt.Printf("This mess is  [ %q ] [%v]\n", bfRead, isPrefix)

    // 解析 JSON 数据使用 json.Unmarshal([]byte(JSON_DATA),JSON对应的结构体) ,也就是说我们在解析 JSON 的时候需要确定 JSON 的数据结构
    res := &Study{}
    json.Unmarshal([]byte(bfRead), &res)
    fmt.Println(res.Cube)

}

2019年3月26日更新:

在定义与JSON 相配套的 struct 时需要注意 json 描述必须与JSON 数据里面的 key 相同,否则 数据会被解析成空值

这是一个错误例子:

看一下结果:

数据没有被 json.Unmarshal() 解析出来,这里 struct 名称也不一致,但是可以使用。我们看下面的例子:

这里数据已经被 json.Unmarshal() 解析出来了

附赠一个 JSON-to-goStruct 转换的网站,这个网站超乎异常的好用。

Convert JSON to Go instantly​mholt.github.io/json-to-go/

我的 GitHub 地址

sober-wang/OpScript​github.com/sober-wang/OpScript/blob/master/goStudy/goJSONRead.go

一名偏爱 Golang 的大数据工程师,虽然我自诩 Python 学的也不错,但我喜欢有挑战的事。也许我哪天争取那天成为 Golang 布道师。


原网址: 访问
创建于: 2022-08-18 15:02:38
目录: default
标签: 无

请先后发表评论
  • 最新评论
  • 总共0条评论