首页 > 解决方案 > 构造一个 JSON 值作为 HTTP 请求的一部分进行 POST

问题描述

我目前正在尝试构建一个变量,将其转换为 JSON 并使用它发布到我的数据库。

但是,每次我尝试发布数据时,它都会返回“JSON 无效”错误,表明它的构造不正确。

我需要传入两个变量,它们通过作为查询值传入作为请求的一部分进行初始化。

有谁知道为什么我的 JSON 无效?

这是我的代码:

dataString := string(` { "credentials_id": "12345", "user_id": "12", "variable1": ` + variable1 + `, "variable2": ` + variable2 + ` }`)

    fmt.Println(dataString)

    req, err = http.NewRequest("POST", "https://api-call-url/bla", strings.NewReader(finalDataString))

    if err != nil {
        log.Print(err)
        fmt.Println("Error was not equal to nil at first stage.")
        os.Exit(1)
    }

    req.Header.Add("apikey", os.Getenv("APIKEY"))
    req.Header.Add("Authorization", "Bearer "+os.Getenv("APIKEY"))
    req.Header.Add("Content-Type", "application/json")
    req.Header.Add("Prefer", "return=representation")

    resp, err = client.Do(req)
    if err != nil {
        fmt.Println("Error posting data to database.")
        os.Exit(1)
    }

    respBody, _ = ioutil.ReadAll(resp.Body)

    w.WriteHeader(resp.StatusCode)
    w.Write(respBody)

标签: go

解决方案


您应该如这些示例json.Marshal中所示的有效负载数据。

所以像:

import (
        "bytes"
        "encoding/json"
        "net/http"
)

[...]

payload, _ := json.Marshal(map[string]string{
        "credentials_id": "12345",
        "user_id":        "12",
        "variable1":      variable1,
        "variable2":      variable2,
})

req, err = http.NewRequest("POST", "https://api-call-url/bla", bytes.NewReader(payload))

[...]

defer resp.Body.Close()

respBody, _ = ioutil.ReadAll(resp.Body)

var data interface{}
json.Unmarshal([]byte(respBody), &data)

你可以在这里找到一个完整的例子。


推荐阅读