首页 > 解决方案 > 如何解码嵌入的json?

问题描述

即使它是嵌套映射并且我提供了映射类型的结构字段,我也无法将 m 解码为值。我不明白为什么?

大多数问题出在结构字段中,我没有将其名称大写,因此它们没有被导出

    id  int //it should be Id  
    values map[interface{}]interface{}//should be Values 

并且映射键不应该是接口类型,它应该是字符串类型

Values map[interface{}]interface{}
//should be Values map[string]interface{} 

文件名与 json 键不匹配,您可以使用struct 标签将它们与 json 键匹配来解决此问题

//the key for the embedded object was m .
// was trying to decode it into struct 
//field and it's name was m .it was like this before fixing it  
type edit struct{
  Id int 
  Values [interface{}]interface{}
}
//and json object was like this 
{
  "id":5,
  "m": {"name":"alice"}
}
package main

import (
    "encoding/json"
    "fmt"
    "log"
    "strings"
)
type edit struct {
    Id  int 
    Values map[string]interface{}
 
 
}
func main() {
    a := `{
        "id":5,
        "values":{
        "name":"alice"
        }
}`
    var s edit
    dec := json.NewDecoder(strings.NewReader(a))
    err := dec.Decode(&s)
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println(s)
}

玩好代码

标签: jsongo

解决方案


您的代码中有几个问题。

  1. edit首先,必须导出结构的所有字段,这意味着您应该将每个字段的第一个字母大写。
    就像下面这样:

    type edit struct {
        Id
        Values
    }
    
  2. key字段的数据类型Values必须是字符串才能解码json数据。

    type edit struct {
        Id     int
        Values map[string]interface{}
    }
    
  3. 最后,您的json数据"id"的数据类型错误。它必须int与您的Go结构相匹配。此外,您的结构中没有"m"定义。"m"必须替换为"values"以匹配您的结构Go。就像下面这样

    {
        "id": 5,
        "values":{
            "name": "alice"
        }
    }
    



只是为了让您知道,您可以简单地使用以下代码将json数据解组到Go结构中。

err := json.Unmarshal([]byte(a), &s)

推荐阅读