gonull
gonull copied to clipboard
Marshalled JSON includes attributes with `Present: false`
In the provided code, when unmarshalling the JSON the Weight
attribute is correctly set to present: false, valid: false
as "Weight"
isn't specified in the JSON.
However, when marshalling the struct back to JSON the output includes the Weight
attribute with a value of null
. This is unexpected as I would assume Present: false
would omit the attribute from the marshalled JSON (and that the marshalled JSON should match the original JSON).
Steps to Reproduce
- Run the following code: (modified from this example in the project
README.md
)
package main
import (
"encoding/json"
"fmt"
"github.com/LukaGiorgadze/gonull"
)
type MyCustomInt int
type MyCustomFloat32 float32
type Person struct {
Name string
Age gonull.Nullable[MyCustomInt] // present: true, valid: true
Address gonull.Nullable[string] // present: true, valid: false
Height gonull.Nullable[MyCustomFloat32] // present: true, valid: false
Weight gonull.Nullable[string] // present: false, valid: false
}
func main() {
jsonData := []byte(`{"Name":"Alice","Age":15,"Address":null,"Height":null}`)
var person Person
err := json.Unmarshal(jsonData, &person)
if err != nil {
panic(err)
}
fmt.Printf("Unmarshalled Person: %+v\n", person)
marshalledData, err := json.Marshal(person)
if err != nil {
panic(err)
}
fmt.Printf("Marshalled JSON: %s\n", string(marshalledData))
}
Expected Behavior
The marshalled JSON should not include the Weight
attribute as it was not present in the original JSON (Present: false
):
{
"Name": "Alice",
"Age": 15,
"Address": null,
"Height": null
}
Actual Behavior
The marshalled JSON includes the Weight
attribute with a value of null
:
{
"Name": "Alice",
"Age": 15,
"Address": null,
"Height": null,
"Weight": null // <-- not expected, this should not be included
}
Environment
-
Go version:
1.22
-
gonull
version:1.2.0
- OS: The Go Playground
Additional Context
This issue was discovered while testing the unmarshalling and marshalling of JSON data with optional fields in the Go Playground. The expected behavior is based on the assumption that Present: false
should result in the attribute being omitted from the marshalled JSON.