How to parse partial objects inside Json

huangapple go评论80阅读模式
英文:

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

huangapple
  • 本文由 发表于 2017年8月24日 11:19:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/45852398.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定