登录
首页 >  Golang >  Go问答

Json请求返回错误的数据格式

来源:stackoverflow

时间:2024-03-22 13:42:27 293浏览 收藏

在 Go 中尝试返回 JSON 时遇到错误,导致接收到的数据格式不正确。错误的根源在于手动创建 JSON 字符串并对其进行 JSON 编码,导致生成无效的 JSON。解决方案包括使用 `fmt.Sprintf` 中的 `%q` 格式化字符串,或使用 `json.Marshal` 函数创建有效的 JSON。

问题内容

我正在尝试在 go 中返回一个简单的 json。这是一个网络应用程序,这是处理程序的一部分:

func jsontest1(w http.responsewriter, r *http.request) {
  test1 := "something1"
  test2 := 456
  j1 := []byte(fmt.sprintf(`
    {
      data: {
        "test1": %s,
        "test2": %d
      }
    }
  `, test1, test2))



  j2, _ := json.marshal(&j1)
  w.header().set("content-type", "application/json")
  w.write(j2)
 }

当我通过curl 发出请求时,我收到类似以下内容的信息:

CiAgICB7CiAgICAgIGRhdGE6IHsKICAgICAgICAicmVkaXJlY3RfdXJsIjogdGVzdF9yZWRpcl91cmwxLAogICAgICAgICJtZXNzYWdlIjogdGVzdCBtc2cgMQogICAgICB9CiAgICB9CiAg
为什么?如何解决这个问题?

解决方案


当您对 []byte 进行 json 编码时,它将呈现为 base64 编码的字符串,这是在 json 中表示任意字节切片/数组的最有效方法(唯一真正的替代方法是 "field": [7, 129, 13, 48, ...] 等)。然而,在您的代码中,您正在执行一些不寻常的操作,这些操作可能不是预期的:

  • 您正在使用 sprintf 手动创建一个 json-ish 字符串,然后尝试对您的 json 进行 json 编码。 json.marshal 用于获取任意 go 值并将其渲染为 json。
  • 您手动创建的 json 无效;您有一个未加引号的字符串字段值。

您想要的可能是以下选项之一:

// Manually-created *valid* JSON
func JsonTest1(w http.ResponseWriter, r *http.Request) {
    test1 := "something1"
    test2 := 456
    // %q instead of %s gives us a quoted string:
    j1 := []byte(fmt.Sprintf(`
    {
      data: {
        "test1": %q,
        "test2": %d
      }
    }
  `, test1, test2))

    w.Header().Set("Content-Type", "application/json")
    w.Write(j1)
}

// JSON created with json.Marshal
func JsonTest2(w http.ResponseWriter, r *http.Request) {
    test1 := "something1"
    test2 := 456
    data := map[string]interface{}{
        "data": map[string]interface{}{
            "test1": test1,
            "test2": test2,
        },
    }
    j1, _ := json.Marshal(data)
    w.Header().Set("Content-Type", "application/json")
    w.Write(j1)
}

以上就是《Json请求返回错误的数据格式》的详细内容,更多关于的资料请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>