如何解决通过 reqBody 和 json unmarshal
客户端当前有一个应用程序,在 JS 中的浏览器中运行计算。计算功能接受收入、支出等财务输入,并进行大量计算,然后绘制一些漂亮的图表并提出一些合理的建议。
我想把它改成 GO API,因为我们将需要更复杂的计算,而旧手机真的不喜欢所有这些计算的任务。
但是我在从 GO 中的输入数据中获取特定输入字段时遇到问题。
目前输入是一个数组数组,例如[收入1、收入2、费用1、费用2等..
每个输入或费用元素本身就是一个数组。所以他们是这样的。
[["Michael J Mouse","Monthly","Wed,12 May 2021 10:59:07 GMT","2500","No","Mon,11 May 2026 10:59:07 GMT"],["Michael J Mouse",null],....and then on to the other items.
收入有名称、频率、开始日期、金额,它们可能结束或不结束,也可能有结束日期(用户,嗯!)以及类似的费用。
我可以使用 JSON stringify 将长输入数组 POST 到 GO API,这样它就可以很好地访问 API。我可以用 fPrintf 回显它。
但是当我尝试解组它时,我最终没有逗号和引号。因此,无法分辨输入的一段在哪里结束,另一段从哪里开始。
[[Michael J Mouse Monthly Wed,12 May 2021 10:59:07 GMT 2500 No Mon,11 May 2026 10:59:07 GMT] [Michael J Mouse Monthly Wed,15 May 2021 14:29:07 GMT 2500 No <nil>]
这是我将数据拉入 GO 时得到的 reqBody。这似乎已经是问题了……没有引号,没有逗号。
然后,当我 unMarshal 时,我将方括号之间的每个部分作为这样的单个元素。
[Michael J Mouse Monthly Wed,11 May 2026 10:59:07 GMT]
[Michael J Mouse Monthly Wed,12 May 2021 10:59:07 GMT 2500 No <nil>]
现在我可以回去重写所有内容,以便客户端在每个字段上发布带有名称的数据,然后定义结构......但我想知道是否有任何方法可以将这样的东西放入数组中......那么我已经有了其他所有代码。
["Michael J Mouse",11 May 2026 10:59:07 GMT"]
我是否遗漏了一些非常简单的东西?
这是代码:
func doCalcuation(w http.ResponseWriter,r *http.Request) {
// get the body of our POST request
reqBody,_ := ioutil.ReadAll(r.Body)
fmt.Println("got to this stage: doCalcuation")
fmt.Fprintf(w,"%+s",string(reqBody))
fmt.Println("This should be then the reqBody")
fmt.Println(len(reqBody))
var datas []interface{}
json.Unmarshal(reqBody,&datas)
fmt.Println("this is after the unmarshalling")
fmt.Println(datas)
解决方法
fmt.Println,不会在数组的每个元素之间显示“,”,如果你想以这种方式打印它,你需要格式化并打印它
var datas [][]string
json.Unmarshal(reqBody,&datas)
fmt.Println("this is after the unmarshalling")
array := []string{}
for _,data := range datas {
array = append(array,fmt.Sprintf("[%s]",strings.Join(data,",")))
}
output := fmt.Sprintf("[%s]",strings.Join(array,"))
fmt.Println(output)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。