通过 reqBody 和 json unmarshal 从 POST 操作中获取数组数组到 GO 计算中

Getting an array of arrays from a POST operation into a GO calculation through reqBody and json unmarshal

客户目前有一个在浏览器中使用 JS 进行计算的应用程序 运行。计算函数接受收入、支出等财务输入,并进行大量计算,然后绘制一些漂亮的图表并提出一些明智的建议。

我想把它改成 GO API 因为我们将需要更复杂的计算,而旧手机真的不喜欢所有这些计算任务。

但我在从 GO 的输入数据中获取特定输入字段时遇到问题。

目前,输入是一个数组数组,例如 [income1、income2、expense1、expense2 等等……

每个输入或费用元素本身就是一个数组。所以他们是这样的。

[["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, 12 May 2021 10:59:07 GMT", "2500", "No", null], 
....and then on to the other items. 

收入有名称、频率、开始日期、金额,它们可能结束也可能没有,并且可能已经给出了结束日期或没有(用户,嗯!)和支出类似。

我可以 POST 将长输入数组 API 与 JSON 字符串化,这样它就可以 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, 12 May 2021 10:59:07 GMT 2500 No Mon, 11 May 2026 10:59:07 GMT] 
[Michael J Mouse Monthly Wed, 12 May 2021 10:59:07 GMT 2500 No <nil>]

现在我可以返回并重写所有内容,以便客户 POST 在每个字段上使用名称的数据,然后定义结构....但我想知道是否有任何方法可以得到这样的东西只是进入一个数组...然后我已经有了所有其余部分的代码。

["Michael J Mouse", "Monthly", "Wed, 12 May 2021 10:59:07 GMT", "2500", "No", "Mon, 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)