go icon indicating copy to clipboard operation
go copied to clipboard

Dynamic field omit/removal/exclude

Open brianvoe opened this issue 5 years ago • 3 comments

Is their a way to dynamically omit or exclude a field from being output to json.

To give you some context we work with structs and depending on the user type we may not want certain users to see certain fields. It would be nice to simply call a method that adds to an array fields that we would like to exclude before marshaling.

brianvoe avatar Jul 23 '19 05:07 brianvoe

I know you probably have a lot of issues to get to. but if i could get any reply on this, that would be great.

Plus if it doesnt exist I would be more than happy to try to integrate it if would be open to accepting it

brianvoe avatar Jul 29 '19 21:07 brianvoe

You can register an extension.

type TestObjectForIssue392 struct {
	DynamicOmitField string
	OtherField       string
}

type OmitFieldExtension struct {
	jsoniter.DummyExtension
}

func (e *OmitFieldExtension) UpdateStructDescriptor(structDescriptor *jsoniter.StructDescriptor) {
	if structDescriptor.Type.String() != reflect.TypeOf(TestObjectForIssue392{}).String() {
		return
	}

	if binding := structDescriptor.GetField("DynamicOmitField"); binding != nil {
		binding.ToNames = []string{}
	}
}

func test() {
	cfg := jsoniter.Config{}.Froze()
	cfg.RegisterExtension(&OmitFieldExtension{})
	if s, err := cfg.MarshalToString(TestObjectForIssue392{"will not marshal", "foo"}); err == nil {
		fmt.Println(s)
		// {"OtherField":"foo"}
	}
}

AllenX2018 avatar Jan 16 '20 11:01 AllenX2018

@AllenX2018 how to get value of the field? I mean want to exclude from json depending on value of the field not the name.

renathoaz avatar Jul 21 '23 01:07 renathoaz