如何在Go lang中解组Json字符串以获得仅一个键的值

时间:2019-04-11 17:04:11

标签: go

所以我需要解码一个json字符串以获得 key ID 的值,但是我无法找到只提取一个键的值的方法,所以我创建了整个json字符串的结构,以便我可以解组以提取信息,但是我认为我的结构存在一些问题,因为我没有任何输出

package main

import (
    "fmt"
    "encoding/json"
)
type season struct{
    Data []seasoninfo `json:"seasoninfo"`
}
type seasoninfo struct{
    Aliases []string
    Banner string
    FirstAired string
    Id int
    Network string
    Overview string
    SeriesName string
    Slug string
    Status string
}
func main() {
    s := `{"data":[{"aliases":[],"banner":"graphical/81189-g21.jpg","firstAired":"2008-01-20","id":81189,"network":"AMC","overview":"Walter White, a struggling high school chemistry teacher, is diagnosed with advanced lung cancer. He turns to a life of crime, producing and selling methamphetamine accompanied by a former student, Jesse Pinkman, with the aim of securing his family's financial future before he dies.","seriesName":"Breaking Bad","slug":"breaking-bad","status":"Ended"},{"aliases":[],"banner":"","firstAired":"","id":356427,"network":"AMC","overview":null,"seriesName":"Breaking Bad: Original Minisodes","slug":"breaking-bad-original-minisodes","status":"Ended"},{"aliases":["Breaking Bad (ES)"],"banner":"graphical/273859-g.jpg","firstAired":"2014-06-08","id":273859,"network":"Univision","overview":"“Metastasis” is the story of a struggling high school chemistry teacher who is diagnosed with inoperable lung cancer. He turns to a life of crime, producing and selling meth with a former student in order to secure his family’s financial future before he passes away.","seriesName":"Metastasis","slug":"metastasis","status":"Ended"}]}`
    var series season
    err:=json.Unmarshal([]byte(s),&series)
    if err==nil{
        fmt.Println(series)
    } else{
        fmt.Println("wrong")
    }
}

输出为{[]}

https://play.golang.org/p/5jYSp4cMCok

谢谢

1 个答案:

答案 0 :(得分:1)

问题是您当前正在尝试将结构字段Data与JSON属性键seasoninfo匹配。但是,您的示例JSON输入没有seasoninfo作为外部属性,而有data作为外部属性。将json:"seasoninfo"更改为json:"data"

type season struct{
  Data []seasoninfo `json:"data"`
}

这是一个example正在起作用。

或更简单的是,您可以考虑将JSON匹配结构字段json:"data"中的data部分删除为Data

这是一个example正在起作用:

type season struct{
    Data []seasoninfo
}

希望有帮助!