我下面有Json结构,我试图只解析对象内的关键字段。没有映射完整的结构就可以做到这一点吗?
{
"Records":[
{
"eventVersion":"2.0",
"s3":{
"s3SchemaVersion":"1.0",
"configurationId":"my-event",
"bucket":{
"name":"super-files",
"ownerIdentity":{
"principalId":"41123123"
},
"arn":"arn:aws:s3:::myqueue"
},
"object":{
"key":"/events/mykey",
"size":502,
"eTag":"091820398091823",
"sequencer":"1123123"
}
}
}
]
}
// Want to return only the Key value
type Object struct {
Key string `json:"key"`
}
答案 0 :(得分:3)
有一些第三方json库非常快速地从json字符串中提取一些值。
库:
GJSON示例:
const json = `your json string`
func main() {
keys := gjson.Get(json, "Records.#.s3.object.key")
// would return a slice of all records' keys
singleKey := gjson.Get(json, "Records.1.s3.object.key")
// would only return the key from the first record
}
答案 1 :(得分:2)
对象是S3的一部分,所以我创建了如下的struct,我能够读取键
type Root struct {
Records []Record `json:"Records"`
}
type Record struct {
S3 SS3 `json:"s3"`
}
type SS3 struct {
Obj Object `json:"object"`
}
type Object struct {
Key string `json:"key"`
}