3

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"`
}
2
  • JSON parsing in Golang is available: golang.org/pkg/encoding/json ... Outside of that you are looking at regex or string functions
    – stampede76
    Commented Aug 24, 2017 at 3:30
  • 1
    Yes. You do not need to include the complete structure. Commented Aug 24, 2017 at 3:41

2 Answers 2

4

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

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.