Skip to content

Instantly share code, notes, and snippets.

@niski84
Created December 15, 2022 05:20
Show Gist options
  • Save niski84/23930c08b1674d61ace1cee5d6444f67 to your computer and use it in GitHub Desktop.
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
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)
}
// 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