Last active
June 20, 2022 12:57
-
-
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/
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This does not take into account that a key might be empty and leaves behind empty keys (e.g.
{"foo":{}}
).