gpt4 book ai didi

go - 如何在 Golang 中解码 Json 字符串以仅获取一个键的值

转载 作者:IT王子 更新时间:2023-10-29 02:07:04 31 4
gpt4 key购买 nike

所以我需要解码一个 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

谢谢

最佳答案

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

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

这是一个 example在行动中。

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

这是一个 example在行动中:

type season struct{
Data []seasoninfo
}

希望对您有所帮助!

关于go - 如何在 Golang 中解码 Json 字符串以仅获取一个键的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55637786/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com