Json marshal, ignore nil, not my struct

I have some types from the Azure SDK, I want to convert to JSON as output from a tool but it is quiet noisy will many nulls, I just want the interesting data.

I know I can create my own structs and òmitempty`but these are structs from another package.


Your question is not clear.

  • Do you want to only parse the interesting fields into a struct?
  • Or do you want to parse the data into an existing struct but print only the non nil fields of this struct?

The Azure SDK returns structs that I do not control

I am writing a cli tool to help me in other tasks that uses the SDK.

My cli tool will write it’s responses to std out by marshaling these SDK structs into json. By default all fields, regardless of their value, will be written to the json output.

I would like to omit nil/null values.

So neither of your options. I don’t have anything to parse. The SDk has already done the parsing,

See the documentation of json.Marshal:

The “omitempty” option specifies that the field should be omitted from the encoding if the field has an empty value, defined as false, 0, a nil pointer, a nil interface value, and any empty array, slice, map, or string.

But if you don’t control the type, you are out of luck.

You could try something like jq to process the JSON.

That’s what I thought.

However, I’ve had an idea, I’ll use https://github.com/fatih/structs to convert the struct to a map then marshal that to json text

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.