如何封送报价和转义报价

I'm marshaling a map[string]interface{} and get a json:

{
    "test": {
        "test2": 123
    }
}

In some cases under an interface{} i have another map[string]interface{}

Is there any way to marshal it and escape double quotes to get json like this?

{
    "test": "{
        \"test2\": 123
    }"
}

(assuming you don't care about the line breaks in your desired output) - one way to do this is to loop through each of the values in your map, and marshal those into a json string first, using the standard json.Marshal function. Then add those strings back into your original map (or a new map if you like). Now that you have a map where the values are actually json string representations of the original values, you can marshal this outer map as json, and the encoder will escape any double quotes in the value strings for you. see this example

package main

import (
    "fmt"
    "encoding/json"
)

var yourMap = map[string]interface{}{
    "a": 1,
    "b": map[string]interface{}{
        "c": 2,
    },
}


func transform(m map[string]interface{}) (map[string]interface{}, error) {
    newMap := make(map[string]interface{})
    for k, v := range m {
        bytez, err := json.Marshal(v)
        if err != nil {
            return nil, err
        }
        newMap[k] = string(bytez)
    }
    return newMap, nil
}

func main() {
    newMap, err := transform(yourMap)
    if err != nil {
        panic(err)
    }

    b, err := json.Marshal(newMap)
    if err != nil {
        panic(err)
    }

    fmt.Println(string(b))
}

a cleaner way to encapsulate the above logic could be to declare a new named type for your map, and implement the custom marshalling in the Marshal method for that new type.