<p>One of my other projects is to create a linux binary that will interface with an API. I'm basically making a CLI tool that can run on linux.</p>
<p>The format is pretty simple for the tool</p>
<p>command subcommand [OPTIONS]</p>
<p>The problem is that the API returns a different JSON structure based on the subcommand</p>
<p>for example:</p>
<pre><code>getapiinfo listusers
</code></pre>
<p>would get me all the users</p>
<p>whereas </p>
<pre><code>getapiinfo listservers
</code></pre>
<p>would get me all the server information. </p>
<p>Obviously the user information and server information is different and there are 100+ subcommands I'm trying to cover and I don't want to build models for all of them because they could also change over time and require maintenance.</p>
<p>So i'm wondering if i get the JSON information back, can i somehow read that data and iterate over it and print out the json data?</p>
<p>or do i have to decode it into a struct?</p>
<p>Thank you. This is a great little community.</p>
<hr/>**评论:**<br/><br/>skarlso: <pre><p>You could always use <code>interface{}</code> to unmarshal arbitrary data. </p>
<pre><code>var f interface{}
err := json.Unmarshal(b, &f)
</code></pre>
<p>Link to article. <a href="https://blog.golang.org/json-and-go" rel="nofollow">https://blog.golang.org/json-and-go</a> </p></pre>retinascan: <pre><p>Oh that's cool. i will take a look at that and plat around with it. Thanks again!</p></pre>skarlso: <pre><p>You're welcome! I really hope it will help you. :-)</p></pre>danhardman: <pre><p>Are you planning on doing anything with the data or do you just need it printed out?</p></pre>retinascan: <pre><p>For now, i just need to print it out really. The data is in JSON but it's really tabular data so I can print it out in columns and print an individual row if needed. Since it's all text, the user can grep for what column they need and assign it to a variable. </p></pre>danhardman: <pre><p>So what you're making basically is cURL but for your API?</p></pre>itsmontoya: <pre><p>You could use map[string]interface{} to maintain object keys and at least search by that.</p>
<p>Also, the json.RawMessage is really useful when you don't need to immediately parse to a struct.</p></pre>
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889
- 请尽量让自己的回复能够对别人有帮助
- 支持 Markdown 格式, **粗体**、~~删除线~~、
`单行代码`
- 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
- 图片支持拖拽、截图粘贴等方式上传