Search code examples
jsongomarshalling

Removing escape characters after Marshalling


In the above code I am trying to convert my key to byte array via Marshal. Although I am successful doing it, when I see the Marshalled string, I am seeing \ escape character before my json keys. Can you please help me remove that?

 func GetBytes(key interface{}) ([]byte, error) {

    b, err := json.Marshal(key)
    if err != nil {
            return nil, err
    }

    log.Println("%%%%%%%%%%")
    log.Printf("%+v\n", key)
    log.Println("##########")
    log.Println(string(b));

    return b, nil
}

Current Output:

%%%%%%%%%%
{"entityId":5010740929,"eventTime":1542706233458}
##########
"{\"entityId\":5010740929,\"eventTime\":1542706233458}"

Solution

  • I think you sending string as key in func GetBytes(key interface{}) ([]byte, error). That's why you are seeing escape characters.

    package main
    
    import (
        "encoding/json"
        "fmt"
        "log"
    )
    
    
    func f(key interface{}) {
        json, err := json.Marshal(key)
        if err != nil {
            log.Fatal(err)
        }
        fmt.Println(string(json))
    }
    
    func main() {
    
        data := map[string]interface{}{
            "A": 1,
            "B": 2,
        }
    
        f(data)
    
        json, err := json.Marshal(data)
        if err != nil {
            log.Fatal(err)
        }
        f(string(json))
    }
    

    Output:

    {"A":1,"B":2}
    "{\"A\":1,\"B\":2}"
    

    Go playground link: https://play.golang.org/p/iF1ckvZ9cQC

    In that case, You can use Unquote to remove quote and escape character:

    package main
    
    import (
        "encoding/json"
        "fmt"
        "log"
        "strconv"
    )
    
    
    func f(key interface{}) {
        json, err := json.Marshal(key)
        if err != nil {
            log.Fatal(err)
        }
        fmt.Println(string(json))
    
        st, err := strconv.Unquote(string(json))
        fmt.Println(st)
    
    }
    
    func main() {
    
        data := map[string]interface{}{
            "A": 1,
            "B": 2,
        }
    
        json, err := json.Marshal(data)
        if err != nil {
            log.Fatal(err)
        }
        f(string(json))
    }
    

    Output:

    "{\"A\":1,\"B\":2}"
    {"A":1,"B":2}
    

    Go playground link: https://play.golang.org/p/aoTEQtJslTs