Skip to content

Conversation

@lingcoder
Copy link
Contributor

Summary

  • Add OmitEmpty option to gjson.Options struct
  • Pass OmitEmpty value to gconv.Map() instead of hardcoding false
  • Add unit tests to verify the new option

Background

When using gjson.New() to convert a struct to JSON, fields with omitempty tag were not being omitted even when their values were empty. This was inconsistent with the standard library json.Marshal() behavior.

Before:

type User struct {
    Age    int `json:"age,omitempty"`
    Height int `json:"height,omitempty"`
}
user := User{Age: 1}
gjson.New(user).String() // {"age":1,"height":0}  - height not omitted
json.Marshal(user)       // {"age":1}             - height omitted

After:

gjson.NewWithOptions(user, gjson.Options{OmitEmpty: true}).String() // {"age":1}

Test plan

  • Add unit test Test_NewWithOptions_OmitEmpty covering:
    • Default behavior (OmitEmpty: false) - empty fields included
    • With OmitEmpty: true - empty fields omitted
    • All empty values scenario

Closes #4450

Add OmitEmpty option to gjson.Options to allow users to control whether
empty values with `omitempty` tag should be omitted when converting
struct to Json object.

Before this change, gjson.New() would always include empty fields even
if they had the `omitempty` tag, which was inconsistent with standard
library json.Marshal() behavior.

Now users can enable OmitEmpty to get behavior consistent with json:
  j := gjson.NewWithOptions(data, gjson.Options{OmitEmpty: true})

Closes gogf#4450
@lingcoder lingcoder closed this Jan 20, 2026
@lingcoder lingcoder deleted the fix/gjson-omitempty-4450 branch January 20, 2026 03:33
@lingcoder
Copy link
Contributor Author

还是放弃修改了,基础库先不动,影响面比较大

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

encoding/gjson: 没有正确处理omitempty

1 participant