Created
October 29, 2024 06:44
-
-
Save olivere/e36967cf347b2b89211a585ed2be7bf2 to your computer and use it in GitHub Desktop.
Normalize JSON
This file contains hidden or 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" | |
"io" | |
"os" | |
"sort" | |
) | |
// normalizeJSON recursively processes JSON data and returns a normalized version | |
func normalizeJSON(data interface{}) interface{} { | |
switch v := data.(type) { | |
case map[string]interface{}: | |
// For objects, sort keys and normalize values | |
normalized := make(map[string]interface{}) | |
keys := make([]string, 0, len(v)) | |
// Collect all keys | |
for k := range v { | |
keys = append(keys, k) | |
} | |
// Sort keys | |
sort.Strings(keys) | |
// Process each value recursively | |
for _, k := range keys { | |
normalized[k] = normalizeJSON(v[k]) | |
} | |
return normalized | |
case []interface{}: | |
// For arrays, normalize each element | |
normalized := make([]interface{}, len(v)) | |
for i, val := range v { | |
normalized[i] = normalizeJSON(val) | |
} | |
return normalized | |
default: | |
// For primitive types, return as-is | |
return v | |
} | |
} | |
func main() { | |
// Read JSON from stdin | |
input, err := io.ReadAll(os.Stdin) | |
if err != nil { | |
fmt.Fprintf(os.Stderr, "Error reading input: %v\n", err) | |
os.Exit(1) | |
} | |
// Parse JSON | |
var data interface{} | |
if err := json.Unmarshal(input, &data); err != nil { | |
fmt.Fprintf(os.Stderr, "Error parsing JSON: %v\n", err) | |
os.Exit(1) | |
} | |
// Normalize the JSON | |
normalized := normalizeJSON(data) | |
// Marshal back to JSON with indentation | |
output, err := json.MarshalIndent(normalized, "", " ") | |
if err != nil { | |
fmt.Fprintf(os.Stderr, "Error encoding JSON: %v\n", err) | |
os.Exit(1) | |
} | |
// Write to stdout | |
fmt.Println(string(output)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment