简体   繁体   English

来自 csv 文件的 JSON 格式的 Golang POST 请求

[英]Golang POST request in JSON format from a csv file

so I am trying to POST a csv file in JSON format to a website in Golang.所以我正在尝试将 JSON 格式的 csv 文件发布到 Golang 的网站。 I have been successful in POSTing a singular JSON file.我已经成功发布了一个单一的 JSON 文件。 However, that is not what I want the purpose of my program to be.但是,这不是我希望我的程序的目的。 Basically, I'm trying to create an account generator for a site.基本上,我正在尝试为网站创建一个帐户生成器。 I want to be able to generate multiple accounts at once.我希望能够一次生成多个帐户。 I feel the best way to do this is with a csv file.我觉得最好的方法是使用 csv 文件。

I've tried using encoding/csv to read the csv file then marshal to JSON.我尝试使用 encoding/csv 来读取 csv 文件,然后编组到 JSON。 Also, ioutil.ReadFile() .另外, ioutil.ReadFile() However, the response from the site is, 'first name is mandatory field, last name is a mandatory field' etc etc. So, this obviously means the csv data is not going into JSON format.但是,该站点的响应是,“名字是必填字段,姓氏是必填字段”等。所以,这显然意味着 csv 数据不会进入 JSON 格式。 I'll show my code with the ioutil.ReadFile() below.我将在下面使用 ioutil.ReadFile() 显示我的代码。

func main() {
file, _ := ioutil.ReadFile("accounts.csv")

    jsonConv, _ := json.Marshal(file)

    client := http.Client{}

    req, err := http.NewRequest("POST", "websiteUrlHere", bytes.NewBuffer(jsonConv))
    req.Header.Add("cookie", `"really long cookie goes here"`)
    req.Header.Set("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36")
    req.Header.Set("content-type", "application/json")

    resp, err := client.Do(req)
    if err != nil {
        fmt.Print(err)
    }
    defer resp.Body.Close()
}

(^ This is just a snippet of the code). (^ 这只是代码片段)。

I'm still pretty new to all of this so please understand if the question lacks anything.我对这一切还是很陌生,所以请理解这个问题是否缺少任何东西。 I've also looked for similar questions but all I find is the use of a struct.我也寻找过类似的问题,但我发现的只是结构的使用。 I feel this wouldn't be applicable for this as the goal is to create unlimited accounts at once.我觉得这不适用于此,因为目标是一次创建无限帐户。

Hope the above is sufficient.希望以上内容就足够了。 Thank you.谢谢你。

The issue with your code is actually that you're trying to convert a file to bytes with:您的代码的问题实际上是您正在尝试将文件转换为字节:

file, _ := ioutil.ReadFile("accounts.csv")

...and then you are AGAIN trying to convert that slice of bytes to JSON bytes with: ...然后您再次尝试将该字节片转换为 JSON 字节:

jsonConv, _ := json.Marshal(file)

Where the text contents of the file are stored as a slice of bytes in the variable file , and then that slice of bytes (the file contents in bytes form) is then being converted to a JSON array of bytes.文件的文本内容作为字节片存储在变量file中,然后该字节片(字节形式的文件内容)被转换为 JSON 字节数组。 So you are basically sending a JSON array of numbers...not good.所以你基本上是在发送一个 JSON 数字数组......不好。

The normal flow here would be to take the file bytes and then create a Go struct(s) out of it.这里的正常流程是获取file字节,然后从中创建一个 Go 结构。 Once your Go objects are in place, THEN you would marshal to JSON.一旦您的 Go 对象就位,那么您将编组到 JSON。 That converts the Go objects to a slice of bytes AFTER it has been converted to JSON text form.在将 Go 对象转换为 JSON 文本形式之后,将其转换为字节片。

So what you are missing is the Go structure middle step but you also should keep in mind that converting a Go struct to JSON bytes with json.Marshal() will only show fields that are exported. So what you are missing is the Go structure middle step but you also should keep in mind that converting a Go struct to JSON bytes with json.Marshal() will only show fields that are exported. Also, usually you should use struct tags to customize exactly how the fields will show up.此外,通常您应该使用 struct 标签来准确自定义字段的显示方式。

Your best bet is just to stick with JSON, forget about the CSV.你最好的选择就是坚持使用 JSON,忘记 CSV。 In your own code example, you are taking a CSV and then trying to convert it to JSON...so, then, just use JSON.在您自己的代码示例中,您正在使用 CSV,然后尝试将其转换为 JSON ......那么,只需使用 JSON。

If you want to send multiple accounts, just make your Go structure a slice, which will marshal into a JSON array, which is basically what you are trying to do.如果您想发送多个帐户,只需将您的 Go 结构设为一个切片,它将编组为 JSON 数组,这基本上就是您想要做的。 The end result will be a JSON array of accounts.最终结果将是 JSON 帐户数组。 Here's a simple example:这是一个简单的例子:

package main

import (
    "fmt"
    "encoding/json"
)

type Account struct {
    Username string `json:"username"`
    Email string `json:"email"`
}

type AccountsRequest struct {
    Accounts []Account `json:"accounts"`
}

func main() {
    //gather account info
    acct1 := Account{Username: "tom", Email: "tom@example.com"}
    acct2 := Account{Username: "dick", Email: "dick@example.com"}
    acct3 := Account{Username: "harry", Email: "harry@example.com"}
    
    //create request
    acctsReq := AccountsRequest{Accounts: []Account{acct1, acct2, acct3}}
    
    //convert to JSON bytes/data
    //jsonData, _ := json.Marshal(acctsReq)
    
    //debug/output
    jsonDataPretty, _ := json.MarshalIndent(acctsReq, "", "  ")
    fmt.Println(string(jsonDataPretty))
    
    //send request with data
    //...
}

Runnable here in playground.操场上运行。

The key is that the structs are set up and ready to go and the struct tags determine what the JSON field names will be (ie username & email for each account and accounts for the overall array of accounts).关键是结构已设置并准备好 go 和结构标签确定 JSON 字段名称将是什么(即usernameemail )并accounts每个数组的帐户。

Hope that helps.希望有帮助。 Drop a comment if you need more specific help.如果您需要更具体的帮助,请发表评论。

You need to parse the CSV file first and convert it into the list that you want:您需要先解析 CSV 文件并将其转换为您想要的列表:

package main


func main() {
   file, err := os.Open("file.csv")
   if err != nil {
      log.Fatal("failed opening file because: %s", err.Error())
   }
   r := csv.NewReader(file)

   records, err := r.ReadAll()
   if err != nil {
      log.Fatal(err)
   }
   fmt.Print(records)
}

The above code is parsing the list into a [][]string array.上面的代码将列表解析为 [][]string 数组。 you will now need to iterate over that array and turn it into the json object that the page needs.您现在需要遍历该数组并将其转换为页面所需的 json object。 Then you can send it.然后就可以发送了。 You can read more about the csv package here: https://golang.org/pkg/encoding/csv/您可以在此处阅读有关 csv package 的更多信息: https://golang.org/pkg/encoding/csv/

A word of advise: never ignore errors, they might give you useful information.一句忠告:永远不要忽略错误,它们可能会给你有用的信息。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM