<p>So I am working with an external service where we get a json from the same endpoint. The trick is that different values are represented by key.</p>
<p>E.g.</p>
<pre><code>{"dhcp":{"option55":"1,3,6,12,15,28,40,41,42"},"mac":"006b9e669ff4"}
{"dhcp":{"option55":"1,3,6,12,15,17,23,28,29,31,33,40,41,42","option60":"VIZIO VIA"},"mac":"006b9ee7f44f"}
{"mac":"00066672eefd","tcp":{"device":"OpenBSD"}}
{"mac":"000666c399e4","tcp":{"device":"ESX"}}
</code></pre>
<p>Now depending upon whether json has the key "dhcp" or "tcp".</p>
<p>I have been trying but I could not find any elegant way to figure this out in golang. All the json unmarshal expects me to pass a struct with a know json path.</p>
<p>What I would like to do is check for the key first and then maybe unmarshal that into different struct accordingly.</p>
<hr/>**评论:**<br/><br/>Veonik: <pre><p>Create a struct that embeds or contains other structs. A very basic proof of concept: <a href="https://play.golang.org/p/ODTals3J-BK" rel="nofollow">https://play.golang.org/p/ODTals3J-BK</a></p>
<p>You could extend this, making the <code>Line</code> struct have a pointer to <code>DHCPLine</code> and <code>TCPLine</code>, which would default to nil -- a simple signal to switch on.</p>
<p>edit: add detail</p></pre>ChristophBerger: <pre><blockquote>
<p>All the json unmarshal expects me to pass a struct with a know json path.</p>
</blockquote>
<p>Not quite correct, <code>json.Unmarshal</code>can unmarshal into anything that implements the <code>Unmarshaler</code>interface, as well as into native datatypes. </p>
<p>You could, for example, unmarshal the data into maps. <a href="https://www.reddit.com/r/golang/comments/7sibjp/help_golang_consume_json_with_dynamic_relevant/" rel="nofollow">Here</a> is a related discussion with solutions.</p></pre>irene634: <pre><p>You can do that with json.Unmarshall. You can umarshall it into a map and then play around with it depending what you need. This can be helpful for you:</p>
<p><a href="https://stackoverflow.com/questions/33436730/unmarshal-json-with-unknown-fields" rel="nofollow">https://stackoverflow.com/questions/33436730/unmarshal-json-with-unknown-fields</a></p>
<p>Another solution is to have two structs as two possible json data that you recieve and go like 1. Unmarshal to first struct, if you get an error that it doesn't match then do 2.Unmarshal to second struct </p>
<p>Don't forget to handle other options such as when it doesn't match any struct. Depending on what you want to achieve you can umarshal it into a map or just return that it is a bad format etc. </p></pre>
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889
0 回复
- 请尽量让自己的回复能够对别人有帮助
- 支持 Markdown 格式, **粗体**、~~删除线~~、
`单行代码`
- 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
- 图片支持拖拽、截图粘贴等方式上传