为了账号安全,请及时绑定邮箱和手机立即绑定

从 JSON 文件中读取数据并将其作为发布请求发送

从 JSON 文件中读取数据并将其作为发布请求发送

Go
互换的青春 2022-09-19 17:26:36
如何从 json 文件中读取数据并将其作为发布请求发送到 uri 终结点。我目前正在学习Go语言,并从事我的第一个学习项目。这是我的示例数据// parent.json{"name":"Jade Copnell","age":16,"gender":"Agender","occupation":"Account Representative II","numbers":"178-862-5967","children":{"name":"Kayne Belsham","age":38,"gender":"Genderqueer","occupation":"Clinical Specialist","interest":"Re-engineered discrete methodology","number":"145-355-4123"},"friends":{"name":"Stephi Aries","age":74,"gender":"Genderqueer","occupation":"Senior Sales Associate","numbers":"873-726-1453","interests":"Self-enabling systematic function","methow":"24/7"}}这就是我写的,当我运行下面的脚本时,我倾向于得到一个类似于下面的数据作为输出,我也得到发送到数据库的空数据。"{\"name\":\"Jade Copnell\",\"age\":16,\"gender\":\"Agender\",\"occupation\":\"Account Representative II\",\"numbers\":\"178-862-5967\",\"children\":{\"name\":\"Kayne Belsham\",\"age\":38,\"gender\":\"Genderqueer\",\"occupation\":\"Clinical Specialist\",\"interest\":\"Re-engineered discrete methodology\",\"number\":\"145-355-4123\"},\"friends\":{\"name\":\"Stephi Aries\",\"age\":74,\"gender\":\"Genderqueer\",\"occupation\":\"Senior Sales Associate\",\"numbers\":\"873-726-1453\",\"interests\":\"Self-enabling systematic function\",\"methow\":\"24/7\"}}"func main() {    // Open the file.    f, _ := os.Open("./go_data/parent.json")    // Create a new Scanner for the file.    scanner := bufio.NewScanner(f)    // Loop over all lines in the file and print them.    for scanner.Scan() {        responseBody := scanner.Text()        postBody, _ := json.Marshal(responseBody)        //fmt.Println(postBody)        time.Sleep(2 * time.Second)        webBody := bytes.NewBuffer(postBody)        // fmt.Println(webBody)        resp, err := http.Post("http://127.0.0.1:5000/v1/parent", "application/json", webBody)        if err != nil {            log.Fatalf("An Error Occured %v", err)        }        time.Sleep(2 * time.Second)        defer resp.Body.Close()    }}
查看完整描述

1 回答

?
阿波罗的战车

TA贡献1862条经验 获得超6个赞

如果您改为这样做,该怎么办?第三个参数到 http。帖子是一个io。读取器接口 - 您的文件“f”实现。


package main


import (

    "bufio"

    "log"

    "net/http"

    "os"

    "time"

)


func main() {

    // Open the file.

    f, _ := os.Open("./go_data/parent.json")


    resp, err := http.Post("http://127.0.0.1:5000/v1/parent", "application/json", f)


    if err != nil {

        log.Fatalf("An Error Occured %v", err)

    }

    time.Sleep(2 * time.Second)

    defer resp.Body.Close()

}


查看完整回答
反对 回复 2022-09-19
  • 1 回答
  • 0 关注
  • 148 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号