Created
December 15, 2022 05:20
-
-
Save niski84/23930c08b1674d61ace1cee5d6444f67 to your computer and use it in GitHub Desktop.
CensorField censors a field in a JSON string by replacing everything after the first three characters with asterisks
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
package main | |
import ( | |
"encoding/json" | |
"fmt" | |
"strings" | |
) | |
// CensorField censors a field in a JSON string by replacing everything after the first three characters with asterisks | |
func CensorField(jsonStr string, field string) (string, error) { | |
// Convert JSON string to map | |
var jsonMap map[string]string | |
err := json.Unmarshal([]byte(jsonStr), &jsonMap) | |
if err != nil { | |
return "", err | |
} | |
// Censor specified field by replacing everything after the first three characters with asterisks | |
jsonMap[field] = strings.Replace(jsonMap[field], jsonMap[field][3:], "***", -1) | |
// Convert map back to JSON string | |
censoredJSON, err := json.Marshal(jsonMap) | |
if err != nil { | |
return "", err | |
} | |
return string(censoredJSON), nil | |
} | |
func main() { | |
// Sample JSON string | |
jsonStr := { | |
"name": "John Doe", | |
"email": "[email protected]", | |
"password": "secret123" | |
} | |
// Censor password field | |
censoredJSON, err := CensorField(jsonStr, "password") | |
if err != nil { | |
fmt.Println(err) | |
return | |
} | |
// Print censored JSON string | |
fmt.Println(censoredJSON) | |
} |
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
// Sample JSON string | |
jsonStr := { | |
"name": "John Doe", | |
"email": "[email protected]", | |
"password": "secret123" | |
} | |
// Censor password field | |
censoredJSON, err := CensorField(jsonStr, "password") | |
if err != nil { | |
fmt.Println(err) | |
return | |
} | |
// Print censored JSON string | |
fmt.Println(censoredJSON) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment