Skip to content

Instantly share code, notes, and snippets.

@fredr
Last active February 4, 2021 20:12
Show Gist options
  • Save fredr/1fe19849fa03d986ffa3009b584d36a8 to your computer and use it in GitHub Desktop.
Save fredr/1fe19849fa03d986ffa3009b584d36a8 to your computer and use it in GitHub Desktop.
Flatten vs nested serialization
package main
import (
"encoding/json"
"fmt"
"cloud.google.com/go/datastore"
)
type Other struct {
Text string
}
type Nested struct {
Other Other
Others []Other
}
type Flatten struct {
Other Other `datastore:",flatten"`
Others []Other `datastore:",flatten"`
}
func main() {
nested := Nested{Other{"X"}, []Other{{"Y"}, {"Z"}}}
flatten := Flatten{Other{"X"}, []Other{{"Y"}, {"Z"}}}
psn, _ := datastore.SaveStruct(&nested)
psf, _ := datastore.SaveStruct(&flatten)
bsn, _ := json.MarshalIndent(psn, "", " ")
fmt.Println(string(bsn))
bsf, _ := json.MarshalIndent(psf, "", " ")
fmt.Println(string(bsf))
}

Nested

[
 {
  "Name": "Other",
  "Value": {
   "Key": null,
   "Properties": [
    {
     "Name": "Text",
     "Value": "X",
     "NoIndex": false
    }
   ]
  },
  "NoIndex": false
 },
 {
  "Name": "Others",
  "Value": [
   {
    "Key": null,
    "Properties": [
     {
      "Name": "Text",
      "Value": "Y",
      "NoIndex": false
     }
    ]
   },
   {
    "Key": null,
    "Properties": [
     {
      "Name": "Text",
      "Value": "Z",
      "NoIndex": false
     }
    ]
   }
  ],
  "NoIndex": false
 }
]

Flatten

[
 {
  "Name": "Other.Text",
  "Value": "X",
  "NoIndex": false
 },
 {
  "Name": "Others.Text",
  "Value": [
   "Y",
   "Z"
  ],
  "NoIndex": false
 }
]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment