Reputation: 529
I'm fetching a subreddit and receiving it as a JSON response.
The problem is that the return is kinda big, with lots of fields, but I just want some of them.
The structure is something like:
data.children.data.fields
Children is an array, so I can't access it like that I suppose, but this is just an example.
I pasted the JSON on QuickType to see what it returns me, the structs are big.
So, is there a way I can get only the fields I want to using json.Unmarshal?
Hope someone can help me, thanks in advance!
Upvotes: 0
Views: 789
Reputation: 1316
You can use a struct with fields that you only want. Look at the example below
package main
import (
"encoding/json"
"fmt"
)
type Test struct {
Field1 int `json:"field1"`
Field2 string `json:"field2"`
}
func main() {
jsonString := `{
"field1": 1,
"field2": "test field 2",
"field3": "test field 3"
}`
t := Test{}
err := json.Unmarshal([]byte(jsonString), &t)
if err != nil {
fmt.Println(err)
}
fmt.Println("\n", t)
}
https://play.golang.org/p/qFLXBiU-fMX
Upvotes: 1