dry0106 2018-01-23 12:55
浏览 38
已采纳

如何在Golang中将结构解编为Map [关闭]

I have a Json:

{
  "id": "me",
  "name": "myname",
  "planets": {
      "EARTH": 3,
      "MARS": 4
  }
}

I don't know how to unmarshal planets field into map[string]int, so I'll get access to the elements without unmarshaling them too like in this example: json to map Golang

Here is the code:

package main

import (
   "encoding/json"
   "fmt"
  )

type User struct {
   ID      string `json:"id"`
   Name    string `json:"name"`
   Planets struct {
       Planet map[string]*json.RawMessage
    } `json:"planets"`
}

 func main() {
    data := `{
      "id": "me",
      "name": "myname",
      "planets": {
      "EARTH": 3,
       "MARS": 4
      }
    }`

   user := &User{}
   err := json.Unmarshal([]byte(data), user)
   if err != nil {
       fmt.Println("ERROR " + err.Error())
   }
    fmt.Println(user.ID)
    fmt.Println(user.Planets.Planet["EARTH"])
  }

fmt.Println(user.Planets.Planet["EARTH"]) - returns

fmt.Println(user.Planets["EARTH"]) - does not support indexing

  • 写回答

1条回答 默认 最新

  • dsl36367 2018-01-23 13:30
    关注

    Here is an example with marshal and unmarshal using your object definition

    package main
    
    import (
        "encoding/json"
        "fmt"
    )
    
    type MyObject struct {
        ID      string         `json:"id"`
        Name    string         `json:"name"`
        Planets map[string]int `json:"planets"`
    }
    
    func main() {
        aa := &MyObject{
            ID:   "123",
            Name: "pepe",
            Planets: map[string]int{
                "EARTH": 3,
                "MARS":  4,
            },
        }
        // Marshal
        out, err := json.Marshal(aa)
        if err != nil {
            fmt.Println(err)
            return
        }
        fmt.Println(string(out))
    
        // Unmarshal
        bb := &MyObject{}
        err = json.Unmarshal(out, bb)
        fmt.Println(bb.ID, bb.Name, bb.Planets)
    
    }
    

    and you can get an element of the map with bb.Planets["EARTH"]

    I hope you can find this useful.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 openwrt双栈NAT
  • ¥15 部分网页页面无法显示!
  • ¥15 怎样解决power bi 中设置管理聚合,详细信息表和详细信息列显示灰色,而不能选择相应的内容呢?
  • ¥15 QTOF MSE数据分析
  • ¥15 平板录音机录音问题解决
  • ¥15 请问维特智能的安卓APP在手机上存储传感器数据后,如何找到它的存储路径?
  • ¥15 (SQL语句|查询结果翻了4倍)
  • ¥15 Odoo17操作下面代码的模块时出现没有'读取'来访问
  • ¥50 .net core 并发调用接口问题
  • ¥15 网上各种方法试过了,pip还是无法使用