douou2026 2016-02-13 07:53
浏览 69
已采纳

将嵌套地图编组到JSON中

I'm trying to marshal this nested map into a JSON string.

map[
  description:Foo Bar
  url:http://foobar.co.uk
  theme_color:#1b1b1b
  markdown:kramdown
  sass:map[
    style:compressed
  ]
  collections:map[
    projects:map[
      output:true
      permalink:/project/:path
    ]
    jobs:map[
      output:true
      permalink:/job/:path
    ]
  ]
  title:Foo Bar
  email:foo@foobarco.uk
]

(Cleaned up output from fmt.Printf("%v", m))

Initially a config file is read and parsed to produce the map, so I don't know the fields in advance, meaning I can't(?) use a struct.

Unmarshalling from YAML into this map of map[string]interface{} works fine, but when I pass this map to json.Marshal, I get the following error.

json: unsupported type: map[interface {}]interface{}

From reading around, I can see that this error is thrown because JSON only supports string keys. What's confusing me, is that the map above doesn't seem to have any non-string keys.

If I remove the nested sass and collections keys, it marshals without any issues.

Is it possible to do some sanity check on the map to confirm that all the keys are infact string and not just interface{} looking like strings?

  • 写回答

1条回答 默认 最新

  • douxi7219 2016-02-13 16:34
    关注

    Most likely, the sub-maps are being created as map[interface{}]interface{} by the YAML parser.

    Print out your map with "%#v" instead of "%v" and you will see the types.

    Here's an example

    package main
    
    import "fmt"
    
    func main() {
        a := map[string]interface{}{
            "A": map[interface{}]interface{}{
                "B": 123,
            },
        }
        fmt.Printf("%#v
    ",a)
    }
    

    Produces:

    map[string]interface {}{"A":map[interface {}]interface {}{"B":123}}
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘