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

问题描述:

So i need to decode a json string to obtain value of key ID but i was not able to find a way to only extract value of only one key so i created a struct of whole json string so that i can unmarshal it to extract info but i think there is some problem with my struct because i don't get any output

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")
    }
}

Output is {[]}

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

Thanks

The issue is that you are currently trying to match struct field Data to JSON property key seasoninfo. However your sample JSON input doesn't have seasoninfo as the outer property, it has data as an outer property. Either change json:"seasoninfo" to json:"data":

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

Here is an an example in action.

Or even simpler you could consider simply removing the json:"data" portion as data in the JSON matches Data of the struct field:

Here is an example in action:

type season struct{
    Data []seasoninfo
}

Hopefully that helps!