Search code examples
arraysjsongo

How to remove one or more fields from JSON-encoded string?


I have a string that contains an array of JSON objects. Using Golang, I want to remove one or more specified fields from each object in the array, and then print the stringified result. I need to apply this field-removal process to a number of different JSON input formats and so I don't want to use a model. Here's some skeleton code with one form of example input and desired output:

package main

import (
    "fmt"
)

func functionDropSpecifiedFields(inputString string, fields []string) string {
    var outputString string

    // Need some logic here to remove each field in array 'fields'!

    return outputString
}

func main() {
    jsonArrayAsString := `[{"name":"Marlon","age":25,"created_at":"2025-02-10T08:51:14.615264Z"},{"name":"Wendy","age":31,"created_at":"2025-11-14T08:46:09.435264Z"}]`
    fieldsToRemove := []string{"created_at"}
    reducedString := functionDropSpecifiedFields(jsonArrayAsString, fieldsToRemove)
    fmt.Println(reducedString)

    // Should print: [{"name":"Marlon","age":25},{"name":"Wendy","age":31}]
}

What logic in functionDropSpecifiedFields will achieve this?


Solution

  • It can be certainly achieved, by first collecting your results into a slice of interface{} types and then process, each entry in the slice as a map[string]interface{}. This way, the encode/decode happens, without knowing the specific object types

    func functionDropSpecifiedFields(inputString string, fields []string) string {
        var result []interface{}
    
        if err := json.Unmarshal([]byte(inputString), &result); err != nil {
            panic(err)
        }
    
        for i := range result {
            if obj, ok := result[i].(map[string]interface{}); ok {
                for _, field := range fields {
                    delete(obj, field)
                }
            }
        }
    
        toJson, err := json.Marshal(result)
        if err != nil {
            panic(err)
        }
    
        return string(toJson)
    }
    

    https://go.dev/play/p/Trzdg-odw23