我尝试将一些数组值放入我发送到浏览器的 JSON 字符串中,并且在浏览器中动态添加一些输入字段时工作正常,但是当我尝试在 Go 上检查来自这些新字段的数据时,我尝试解码相同的数据但不工作,因为值是空的。
这是代码:
package main
import "fmt"
import "encoding/json"
type PublicKey struct {
Name string `json:"name"`
Type string `json:"type"`
Description string `json:"description"`
Values []string `json:"values"`
}
func main() {
keysBody := []byte(`
[
[
{
"name":"fecha_inicio",
"type":"date",
"description":"Fecha de Inicio",
"values":[
""
]
}
],
[
{
"name":"fecha_final",
"type":"date",
"description":"Fecha Final",
"values":[
""
]
}
],
[
{
"name":"username",
"type":"select",
"description":"Usuario",
"values":[
"admin",
"gus"
]
}
]
]
`)
keys := make([]PublicKey,0)
json.Unmarshal(keysBody, &keys)
fmt.Printf("%#v", keys)
}
https://play.golang.org/p/kKT3IN4_8vb
这是结果:
[]main.PublicKey{main.PublicKey{Name:"", Type:"", Description:"", Values:[]string(nil)}, main.PublicKey{Name:"",类型:“”,说明:“”,值:[]string(nil)},main.PublicKey{Name:“”,类型:“”,说明:“”,值:[]string(nil)}}
这是在 javascript 中工作正常的相同代码:
parameterData 包含相同的 JSON 字符串
var jsonMenus = JSON.parse(parameterData);
for (let i = 0; i < jsonMenus.length; i++) {
let arr = jsonMenus[i];
for (let j = 0; j < arr.length; j++) {
//New DIV
var newDiv = document.createElement("div");
newDiv.setAttribute("class","w3-quarter");
//console.log(arr[j].name + ' ' + arr[j].type + ' ' + arr[j].description);
var label = document.createElement("Label");
label.innerHTML = arr[j].description;
label.setAttribute("class","w3-label");
newDiv.appendChild(label);
if (arr[j].type != 'select') {
var input = document.createElement("input");
input.type = arr[j].type;
input.name = arr[j].name;
input.setAttribute("class","w3-input w3-border w3-round");
newDiv.appendChild(input);
} else {
var select = document.createElement("select");
select.name = arr[j].name;
var values = arr[j].values
for (let k = 0; k < values.length; k++) {
opt = document.createElement('option');
opt.value = values[k];
opt.innerHTML = values[k];
select.appendChild(opt);
}
select.setAttribute("class","w3-input w3-border w3-round");
newDiv.appendChild(select);
}
container.appendChild(newDiv);
任何人都可以帮助让 JSON 字符串在两个地方都起作用吗?
最佳答案
您的 json 是一个二维数组,但您正试图解码为一维数组。
您需要解码为 [][]PublicKey
,这里是调整后的 playground:https://play.golang.org/p/ykzzqtSPJCU .
关于javascript - JSON 解码数组不起作用,但相同的数据适用于 javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55284050/