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"`
}
1
  • JSON parsing in Golang is available: golang.org/pkg/encoding/json ... Outside of that you are looking at regex or string functions Commented Aug 24, 2017 at 3:30

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
}
Sign up to request clarification or add additional context in comments.

Comments

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 Comment

Or with anonymous structs, like so: play.golang.org/p/6vxCVu7i0C

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.