Unmarshal json into map[interface{}]interface{}

xuanbao · · 1174 次点击    
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
<p>How can I tell golang to unmarshal a JSON into a map[interface{}]interface{}?</p> <p>Would I need to write my own json.Unmarshal()? Can anyone point me to a resource to help with that.</p> <p>The actual issue is that I need to change an existing codebase where map[interface{}]interface{} is used in a lot of places and there are lots of assertions like v.(map[interface{}]interface{}) which means that I will need to make a lot of changes in an already fragile codebase. How do I solve this issue?</p> <hr/>**评论:**<br/><br/>trevorstarick: <pre><p><code>map[string]interface{}</code> might be a better choice if you&#39;re able to do so. It should let you unmarshal the first level of your JSON content and then you can do some type assertions on each of the interfaces.</p> <p>Here&#39;s an example of how you can go along and write a custom Marshaler and Unmarshaler: <a href="https://play.golang.org/p/7nk5ZEbVLw" rel="nofollow">https://play.golang.org/p/7nk5ZEbVLw</a></p></pre>hashhar: <pre><p>Thanks for the example. Will look into it and let you know how it goes.</p></pre>commaok: <pre><p>Also check out raw message <a href="https://golang.org/pkg/encoding/json/#RawMessage" rel="nofollow">https://golang.org/pkg/encoding/json/#RawMessage</a></p></pre>vedhavyas: <pre><p>If the map[interface{}]interface{} is marshaled and unmarshalled to/from JSON, then you can safely replace it with map[string]interface{} and remove key type assertions.</p></pre>hashhar: <pre><p>Thanks. But the biggest issue is tracking down all such assertions. Is there any way to track down all assertions in a golang project?</p> <p>This is obviously the best way to proceed but would require a lot of effort. I guess I better get started then.</p></pre>theOtherOtherBob: <pre><blockquote> <p>Is there any way to track down all assertions in a golang project?</p> </blockquote> <p>grep something like <code>[.](.*)</code>?</p></pre>vedhavyas: <pre><p>grep maybe?</p></pre>

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

1174 次点击  
加入收藏 微博
0 回复
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传