Created
December 2, 2019 15:48
-
-
Save seanpianka/0225fe1a0ff77c55f6c420bf1457c83e to your computer and use it in GitHub Desktop.
Dynamically removing keys from an arbitrary JSON object or JSON object array in Go 1.13
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
import ( | |
"encoding/json" | |
) | |
// Given an input slice of bytes representing an arbitrary JSON object and a slice of strings containing keys | |
// which should not exist in the input JSON object, remove these keys from original object. | |
func removeKeysFromJSONObject(input *map[string]json.RawMessage, keys []string) { | |
for _, key := range keys { | |
delete(*input, key) | |
} | |
} | |
func RemoveKeysFromJSONObjectBytes(input *[]byte, keys []string) error { | |
var output map[string]json.RawMessage | |
if err := json.Unmarshal(*input, &output); err != nil { | |
return err | |
} | |
err := RemoveKeysFromJSONObject(&output, keys) | |
if err != nil { | |
return err | |
} | |
outputBytes, err := json.Marshal(&output) | |
if err != nil { | |
return err | |
} | |
*input = outputBytes | |
return nil | |
} | |
func RemoveKeysFromJSONObject(input *map[string]json.RawMessage, keys []string) error { | |
removeKeysFromJSONObject(input, keys) | |
return nil | |
} | |
func mapFuncToJsonObjectArray(fn func(input *map[string]json.RawMessage) error, jsonArray *[]map[string]json.RawMessage) error { | |
for _, jsonArrayItem := range *jsonArray { | |
err := fn(&jsonArrayItem) | |
if err != nil { | |
return err | |
} | |
} | |
return nil | |
} | |
// Given a function which accepts an arbitrary JSON object, map this function and its outputs onto a provided | |
// arbitrary array of JSON objects. | |
func MapFuncToJsonObjectArrayBytes(fn func(input *map[string]json.RawMessage) error, jsonArray *[]byte) error { | |
var output []map[string]json.RawMessage | |
if err := json.Unmarshal(*jsonArray, &output); err != nil { | |
return err | |
} | |
err := MapFuncToJsonObjectArray(fn, &output) | |
if err != nil { | |
return err | |
} | |
// https://stackoverflow.com/a/24229303/4562156 | |
// The value passed to json.Marshal must be a pointer for json.RawMessage to work properly. | |
outputBytes, err := json.Marshal(&output) | |
if err != nil { | |
return err | |
} | |
*jsonArray = outputBytes | |
return nil | |
} | |
func MapFuncToJsonObjectArray(fn func(input *map[string]json.RawMessage) error, jsonArray *[]map[string]json.RawMessage) error { | |
return mapFuncToJsonObjectArray(fn, jsonArray) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment