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}}
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥88 实在没有想法,需要个思路
  • ¥15 python中合并修改日期相同的CSV文件并按照修改日期的名字命名文件
  • ¥15 有赏,i卡绘世画不出
  • ¥15 如何用stata画出文献中常见的安慰剂检验图
  • ¥15 c语言链表结构体数据插入
  • ¥40 使用MATLAB解答线性代数问题
  • ¥15 COCOS的问题COCOS的问题
  • ¥15 FPGA-SRIO初始化失败
  • ¥15 MapReduce实现倒排索引失败
  • ¥15 ZABBIX6.0L连接数据库报错,如何解决?(操作系统-centos)