douluozhan4370 2018-11-20 09:54
浏览 45
已采纳

编组后删除转义符

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
", key)
    log.Println("##########")
    log.Println(string(b));

    return b, nil
}

Current Output:

%%%%%%%%%%
{"entityId":5010740929,"eventTime":1542706233458}
##########
"{\"entityId\":5010740929,\"eventTime\":1542706233458}"
  • 写回答

1条回答 默认 最新

  • douningchang3610 2018-11-20 10:08
    关注

    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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥200 如何使用postGis实现最短领规划?
  • ¥15 pyinstaller打包错误
  • ¥20 cesm的气溶胶排放文件
  • ¥15 逐月累计,月份不连续,补齐月份
  • ¥15 应用简单的Python代码完成一个学生成绩管理系统
  • ¥15 用matlab求微分方程初值问题
  • ¥15 vscode下编写第三方库opencv与pcl代码时没有代码提示
  • ¥15 能够跑通不报错,如何解决?(标签-matlab)
  • ¥15 MOS在RDS较大,频率高时开关波形异常
  • ¥15 SCENIC分析报错求解答