The encoding/json Decoder is a package in Go that allows you to decode JSON data into Go values. It is part of the standard library and can be imported with "encoding/json".
Example 1: Decode JSON into a Go struct
package main
import ( "encoding/json" "fmt" "strings" )
type Person struct { Name string `json:"name"` Age int `json:"age"` }
var person Person err := decoder.Decode(&person) if err != nil { // handle error }
fmt.Println(person.Name, person.Age) }
In this example, we are decoding a JSON string into a Go struct called "Person". We create a new JSON decoder by passing a reader to the json.NewDecoder function. We then call decoder.Decode to decode the JSON data into the "person" variable.
var numbers []int err := decoder.Decode(&numbers) if err != nil { // handle error }
fmt.Println(numbers) }
In this example, we are decoding a JSON array into a Go slice of integers. We create a new JSON decoder and pass a reader to it. We then call decoder.Decode with a pointer to a slice of integers, which the decoder will fill with the JSON data.
Both examples illustrate the use of the encoding/json package to decode JSON data into Go values.
Golang Decoder - 30 examples found. These are the top rated real world Golang examples of encoding/json.Decoder extracted from open source projects. You can rate examples to help us improve the quality of examples.