Skip to content

Instantly share code, notes, and snippets.

@ribice
Last active June 20, 2022 12:57
Show Gist options
  • Save ribice/074ad38d9f2fc5c88b20663659988d19 to your computer and use it in GitHub Desktop.
Save ribice/074ad38d9f2fc5c88b20663659988d19 to your computer and use it in GitHub Desktop.
Remove null values from JSON with Golang - https://www.ribice.ba/golang-null-values/
func removeNulls(m map[string]interface{}) {
val := reflect.ValueOf(m)
for _, e := range val.MapKeys() {
v := val.MapIndex(e)
if v.IsNil() {
delete(m, e.String())
continue
}
switch t := v.Interface().(type) {
// If key is a JSON object (Go Map), use recursion to go deeper
case map[string]interface{}:
removeNulls(t)
}
}
}
@lukasmalkmus
Copy link

This does not take into account that a key might be empty and leaves behind empty keys (e.g. {"foo":{}}).

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