patterngoMajor
Unmarshaling json in Go: required field?
Viewed 0 times
fieldrequiredunmarshalingjson
Problem
Is it possible to generate an error if a field was not found while parsing a JSON input using Go?
I could not find it in documentation.
Is there any tag that specifies the field as required?
I could not find it in documentation.
Is there any tag that specifies the field as required?
Solution
There is no tag in the
To check for missing fields, you will have to use pointers in order to distinguish between missing/null and zero values:
Full working example:
Playground
encoding/json package that sets a field to "required". You will either have to write your own MarshalJSON() method, or do a post check for missing fields.To check for missing fields, you will have to use pointers in order to distinguish between missing/null and zero values:
type JsonStruct struct {
String *string
Number *float64
}Full working example:
package main
import (
"fmt"
"encoding/json"
)
type JsonStruct struct {
String *string
Number *float64
}
var rawJson = []byte(`{
"string":"We do not provide a number"
}`)
func main() {
var s *JsonStruct
err := json.Unmarshal(rawJson, &s)
if err != nil {
panic(err)
}
if s.String == nil {
panic("String is missing or null!")
}
if s.Number == nil {
panic("Number is missing or null!")
}
fmt.Printf("String: %s Number: %f\n", *s.String, *s.Number)
}Playground
Code Snippets
type JsonStruct struct {
String *string
Number *float64
}package main
import (
"fmt"
"encoding/json"
)
type JsonStruct struct {
String *string
Number *float64
}
var rawJson = []byte(`{
"string":"We do not provide a number"
}`)
func main() {
var s *JsonStruct
err := json.Unmarshal(rawJson, &s)
if err != nil {
panic(err)
}
if s.String == nil {
panic("String is missing or null!")
}
if s.Number == nil {
panic("Number is missing or null!")
}
fmt.Printf("String: %s Number: %f\n", *s.String, *s.Number)
}Context
Stack Overflow Q#19633763, score: 87
Revisions (0)
No revisions yet.