英文:
How to parse partial objects inside Json
问题
我有以下的Json结构,我想解析对象内部的key字段。有没有可能在不映射完整结构的情况下做到这一点?
{
"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"
}
}
}
]
}
// 只想返回Key的值
type Object struct {
Key string json:"key"
}
英文:
I have the Json structure below, and i'm trying to parse only the key field inside the object. It's possible to do it without mapping the complete structure?
{
"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"`
}
答案1
得分: 3
有几个第三方的JSON库非常快速,可以从JSON字符串中提取特定的值。
库:
GJSON示例:
const json = `your json string`
func main() {
keys := gjson.Get(json, "Records.#.s3.object.key")
// 返回所有记录的键的切片
singleKey := gjson.Get(json, "Records.1.s3.object.key")
// 只返回第一条记录的键
}
英文:
There are a few 3rd party json libraries which are very fast at extracting only some values from your json string.
Libraries:
GJSON example:
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
}
答案2
得分: 2
对象是S3的一部分,所以我创建了以下结构体,并且能够读取键值。
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"`
}
英文:
Object is part of S3, so I created struct as below and I was able to read key
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"`
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论