gpt4 book ai didi

json - 如何解码不同数据类型的 JSON 数组?

转载 作者:数据小太阳 更新时间:2023-10-29 03:36:53 26 4
gpt4 key购买 nike

我尝试解码的部分 JSON 有一个数组,可以包含字符串或整数。我将如何解析它?

{
"id": "abc",
"values": [1,2,3]
},
{
"id": "def",
"values": ["elephant", "tomato", "arrow"]
},
{
//etc...
}

我尝试了以下方法:

type Thing struct {
ID string `json:"id"`
Values []string `json:"values,string,omitempty"`
}

得到如下错误:

panic: json: cannot unmarshal array into Go struct field Thing.values of type string

最佳答案

您可以将字段 Values 的类型设置为 []interface{},但您可能必须使用一些类型断言。

这是我使用您提供的数据的 playground 的链接:https://play.golang.org/p/ahePgggr8o1

无论如何我都会把代码贴在这里:

package main

import (
"fmt"
"encoding/json"
)

type Thing struct {
ID string `json:"id"`
Values []interface{} `json:"values,omitempty"`
}

func print(values []interface{}) {
for _, v := range values{
switch value := v.(type){
case string:
fmt.Println("String", value)
case int:
fmt.Println("Integer", value)
case float64:
fmt.Println("Floats", value)
default:
fmt.Printf("I don't know about type %T!\n", v)
}
}
}

func main() {
var t1, t2 Thing
data := []byte("{ \"id\": \"abc\", \"values\": [1,2,3]}")
data2 := []byte("{ \"id\": \"def\", \"values\": [\"elephant\", \"tomato\", \"arrow\"]}")
_ = json.Unmarshal(data, &t1)
_ = json.Unmarshal(data2, &t2)
print(t1.Values)
print(t2.Values)
}

关于json - 如何解码不同数据类型的 JSON 数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50701215/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com