简体   繁体   English

如何发送正确的 JSON 响应消息格式

[英]How to send the correct JSON response message format

I have a Go program which I want to print the JSON response message:我有一个 Go 程序,我想打印 JSON 响应消息:

func MyPluginFunction(w http.ResponseWriter, r *http.Request) {
  data := `{"status":"false","error":"bad request"}`
  w.Header().Set("Content-Type", "application/json")
  w.WriteHeader(http.StatusBadRequest )
  json.NewEncoder(w).Encode(data)
}

However, when I used this function, I got a weird format in the JSON format.但是,当我使用这个 function 时,我得到了 JSON 格式的奇怪格式。 It looks like this:它看起来像这样:

"{\"status\":\"false\",\"error\":\"bad request\"}"

Is there any way to make the response message becomes a normal JSON, like:有什么办法可以让响应消息变成正常的JSON,比如:

{
  "status": "false",
  "error": "bad request"
}

Your data already contains JSON encoded data, so you should just write it as-is, without re-encoding it:您的data已经包含 JSON 编码数据,因此您应该按原样编写,无需重新编码:

func MyPluginFunction(w http.ResponseWriter, r *http.Request) {
    w.Header().Set("Content-Type", "application/json")
    w.WriteHeader(http.StatusBadRequest )
    data := `{"status":"false","error":"bad request"}`
    if _, err := io.WriteString(w, data); err != nil {
        log.Printf("Error writing data: %v", err)
    }
}

If you pass data to Encoder.Encode() , it is treated as a "regular" string and will be encoded as such, resulting in a JSON string where double quotes are escaped as per JSON rules.如果您将data传递给Encoder.Encode() ,它将被视为“常规”字符串并将被编码,从而产生一个 JSON 字符串,其中双引号根据 JSON 规则进行转义。

You only have to JSON encode if you have a non-JSON Go value, such as in this example:如果您有非 JSON Go 值,则只需 JSON 编码,例如在此示例中:

func MyPluginFunction(w http.ResponseWriter, r *http.Request) {
    w.Header().Set("Content-Type", "application/json")
    w.WriteHeader(http.StatusBadRequest)

    data := map[string]any{
        "status": "false",
        "error":  "bad request",
    }
    if err := json.NewEncoder(w).Encode(data); err != nil {
        log.Printf("Error writing data: %v", err)
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何转换 JSON 格式的 debezium 消息,以便将其加载到 Redshift - How to transform a debezium message in JSON format such that it can be loaded into Redshift 如何手动将消息发送到 FirebaseMessagingService 的实例? - How to manually send a Message to an instance of FirebaseMessagingService? JSON 在 beforeCreate 阻塞期间修改用户时的响应格式 function(Google 身份平台) - JSON response format when modifying user during beforeCreate blocking function (Google Identity Platform) 如何使用 sns 消息过滤器发送到特定的 email? - How to use sns message filter to send to particular email? 如何在不通知的情况下向 ios 应用程序发送数据消息? - How to send a Data Message without notification to ios app? 如何通过仅过滤所需信息来格式化 JSON 文件数据? - How to format JSON file data by filtering only info needed? 如何使用 JSON 数据发送 POST 方法 (java)? - How do i Send POST method with the JSON data (java)? 我怎么知道我的 GCM 消息是否足够小 (&lt; 4kb) 可以发送? (如何获取字符串的大小?) - How do i know if my GCM Message is small enough (< 4kb) to send? (How to get size of String?) 如何修改 logstash 以便将失败消息发送到 SQS DLQ - How to modify logstash in order to send failed message to SQS DLQ 如何解析协议缓冲区消息并从中创建 json? - How to parse protocol buffer message and create json out of it?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM