Arrays 解码map和array json
如果没有项,则外部API返回空数组:Arrays 解码map和array json,arrays,json,parsing,dictionary,go,Arrays,Json,Parsing,Dictionary,Go,如果没有项,则外部API返回空数组: {"items":[]} …或带有项目的地图: {"items":{"1": {...}, "2": {...}}} 我怎样才能把它们都解码?我尝试使用此结构: var response struct { Items map[string]Item Array []Item `json:"items"` } 但它不起作用 更新:如果两个(数组和对象)都将生成一个map[string]项,则最好使用此操作代码(a): 主程序包 进口( “
{"items":[]}
…或带有项目的地图:
{"items":{"1": {...}, "2": {...}}}
我怎样才能把它们都解码?我尝试使用此结构:
var response struct {
Items map[string]Item
Array []Item `json:"items"`
}
但它不起作用
更新:如果两个(数组和对象)都将生成一个map[string]项,则最好使用此操作代码(a):
主程序包
进口(
“编码/json”
“fmt”
)
类型项int
类型响应结构{
Items映射[string]Item`json:“Items”`
数组[]项`json:“数组”`
}
func main(){
var d响应
err:=json.Unmarshal([]字节(`Items:{A:1,“B:2,”C:3},“数组:[]}'),&d)
如果错误!=零{
恐慌(错误)
}
fmt.Println(d)
}
输出:
{map[C:3 A:1 B:2] []}
{map[C:3 A:1 B:2]}
{"Items":{"A":1,"B":2,"C":3},"Array":[]}
{map[A:1 B:2 C:3] []}
请尝试此工作代码(B):
主程序包
进口(
“编码/json”
“fmt”
)
类型项int
类型响应结构{
Items映射[string]Item`json:“Items”`
//数组[]项`json:“数组”`
}
func main(){
var d响应
err:=json.Unmarshal([]字节(`Items:{A:1,“B:2,”C:3},“数组:[]}'),&d)
如果错误!=零{
恐慌(错误)
}
fmt.Println(d)
}
输出:
{map[C:3 A:1 B:2] []}
{map[C:3 A:1 B:2]}
{"Items":{"A":1,"B":2,"C":3},"Array":[]}
{map[A:1 B:2 C:3] []}
您可以使用json.Marshal
和json.Unmarshal
,如以下工作代码(C):
主程序包
进口(
“编码/json”
“fmt”
)
类型项int
类型响应结构{
Items映射[string]Item`json:“Items”`
数组[]项`json:“数组”`
}
func main(){
var测试=响应{
条目:映射[string]条目{“A”:1,“B”:2,“C”:3},
数组:[]项{},
}
body,err:=json.Marshal(测试)
如果错误!=零{
恐慌(错误)
}
fmt.Println(string(body))/{“Items”:{“A”:1,“B”:2,“C”:3},“Array”:[]}
var d响应
err=json.Unmarshal(body,&d)
如果错误!=零{
恐慌(错误)
}
fmt.Println(d)
}
输出:
{map[C:3 A:1 B:2] []}
{map[C:3 A:1 B:2]}
{"Items":{"A":1,"B":2,"C":3},"Array":[]}
{map[A:1 B:2 C:3] []}
您可以将{A:1,“B:2,“C:3}
解组到映射[A:1b:2c:3]
和“[1,2,3]”
至[1,2,3]
,如以下工作代码(D):
主程序包
进口(
“编码/json”
“fmt”
)
类型项int
键入response1映射[字符串]项
类型响应2[]项
func main(){
变量d响应1
err:=json.Unmarshal([]字节(`A:1,B:2,C:3}`),和d)
如果错误!=零{
恐慌(错误)
}
fmt.Println(d)//映射[A:1b:2c:3]
风险值d2响应2
err2:=json.Unmarshal([]字节(`1,2,3]`),&d2)
如果err2!=nil{
恐慌(err2)
}
格式打印LN(d2)/[1 2 3]
}
输出:
map[A:1 B:2 C:3]
[1 2 3]
如果需要解组到变量类型,最简单的方法是将其解组到map[string]接口{}
中,然后键入assert(或者在本例中,键入switch)以退出
func Unmarshal(data []byte) (map[string]Item, error) {
var d struct {
Items interface{} `json:"items"`
}
if err := json.Unmarshal(data, &d); err != nil {
return nil, err
}
switch dv := d.Items.(type) {
case []interface{}:
if len(dv) == 0 {
return nil, nil
}
case map[string]interface{}:
m := make(map[string]Item)
for k, v := range dv {
m[k] = Item(v)
}
return m, nil
}
// fallthrough return if different type, or non-empty array
// Could have put this in a default case, but this catches non-empty arrays too
return nil, fmt.Errorf("unexpected type in json")
}
这里有一个示例显示它对您提供的两个示例都有效:请注意我想要解码现有json的内容,我有一个键和两种类型的value@Amd阅读问题,请数组总是空的,它应该是空的map[string]Item{}
对象总是被填充的,所以它应该被填充map[string]Item{…}
@Amd它应该在类型的映射[字符串]项的字段中解码数组
或对象