如何在Golang中发送硬编码的复杂json响应

I am trying to send some complex data as JSON response to one of my rest APIs as follows:

   y := "[ { \"region\":\"North America\", \"countries\":[{\"country\" : \"United States of America\",\"states\"" +
    ":[\"California\", \"New York\", ], }, {\"country\" : \"Canada\",\"states\" : [\"Ontario\", \"Quebec\",], }] }," +
    "{\"region\": \"Asia\",\"countries\": [{\"country\" :\"China\",\"states\" : [\"Fujian\", \"Guangzhou\" ]}, {" +
    "\"country\" : \"Japan\", \"states\" : [ \"Kyushu\", \"Hokaido\" ] }  ]  }]"

    x, err := json.Marshal(y)
    fmt.Println(err)

    c.JSON(200, string(x))

In response I get:

"\"[ { \"region\":\"North America\", \"countries\":[{\"country\" : \"United States of America\",\"states\":[\"California\", \"New York\", ], }, {\"country\" : \"Canada\",\"states\" : [\"Ontario\", \"Quebec\",], }] },{\"region\": \"Asia\",\"countries\": [{\"country\" :\"China\",\"states\" : [\"Fujian\", \"Guangzhou\" ]}, {\"country\" : \"Japan\", \"states\" : [ \"Kyushu\", \"Hokaido\" ] }  ]  }]\""

How do I get rid of these trailing \ in the response? If I remove them from y, the code does not compile.

If you already have the JSON encoded string, you do not need Marshal, you just need to send down the string. By Marshalling here you are encoding your JSON string into a JSON string so Go is escaping it. Just send down the string if you have it.

I think the OP is more concerned about the backslashes in his JSON string than the unnecessary json.Marshal (more on that below)

You can use strconv.Unquote on your JSON string to clean up the back slashes.

s, _ := strconv.Unquote(y) fmt.Println(s)

You don't need to Marshal y, which turns it into bytes then convert it back into a string. You can pass y right down to c.JSON

You want to use Marshal when you have a struct that you want to bundle into JSON.