json - 从 JSON 文件中读取数据并将其作为 Post 请求发送
问题描述
如何从 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()
}
}
解决方案
如果你这样做会怎么样。http.Post 的第三个参数是一个 io.Reader 接口——你的文件“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()
}
推荐阅读
- python - 使用 Python 多处理加速从 Postgres 获取大表到 CSV
- python-3.x - 将过滤后的数据帧的索引作为值返回
- symfony - CollectionType 中的 symfony 表单 CheckboxType = 原型为空
- angular - Angular 7 mat-table 每行可重用组件
- scrapy - Scrapy:通过单击按钮查找 HTTP 调用
- sparql - 在 Sparql 中省略变量会改变结果
- android - Android 存储空间显示不正确的数量
- angular - 如何加载一个组件而不显示其他组件
- postgresql - 创建扩展在 PostgresSQL 中不起作用
- javascript - 如何在一个生成函数中使用一个高阶函数的变量?