Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to parse partial objects inside Json

Tags:

json

parsing

go

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"`
}
like image 683
Vipercold Avatar asked Jun 06 '26 15:06

Vipercold


2 Answers

There are a few 3rd party json libraries which are very fast at extracting only some values from your json string.

Libraries:

  • http://jsoniter.com/
  • https://github.com/tidwall/gjson
  • https://github.com/buger/jsonparser

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
}
like image 99
S. Diego Avatar answered Jun 10 '26 03:06

S. Diego


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"`
}
like image 27
Aswartha Avatar answered Jun 10 '26 03:06

Aswartha



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!