I'm parsing a large JSON file in Go where I need to take only specific items from the JSON.
It's usually a very large file, but eventually, it becomes this:
"textAnnotations": [
{
"boundingPoly": {
"vertices": [
{
"x": 136,
"y": 119
},
{
"x": 5606,
"y": 119
},
{
"x": 5606,
"y": 3985
},
{
"x": 136,
"y": 3985
}
]
},
"description": "Description",
"locale": "en"
},
{
"boundingPoly": {
"vertices": [
{
"x": 3420,
"y": 122
},
{
"x": 3439,
"y": 122
},
{
"x": 3439,
"y": 144
},
{
"x": 3420,
"y": 144
}
]
},
"description": "10"
},
{
"boundingPoly": {
"vertices": [
{
"x": 4106,
"y": 119
},
{
"x": 4128,
"y": 119
},
{
"x": 4128,
"y": 141
},
{
"x": 4106,
"y": 141
}
]
},
"description": "12"
},
I need to take the vertices and description of all of the "boundingPoly"'s in that are within "textAnnotations". I've looked at a few JSON parsing libraries but none seem to do exactly what I'm asking for.
You just need your go structure laid out correctly.
Something like this:
type YourType struct {
TextAnnotations []struct {
BoundingPoly struct {
Vertices []struct {
X int `json:"x"`
Y int `json:"y"`
} `json:"vertices"`
} `json:"boundingPoly"`
Description string `json:"description"`
Locale string `json:"locale,omitempty"`
} `json:"textAnnotations"`
}
The rest is pretty straight forward: https://play.golang.org/p/ICtREyQyjF
You can auto-generate a Go struct from a JSON example using this tool: https://mholt.github.io/json-to-go/
I'm using it every time I need to create a struct for a complex JSON object.