is there a way to print JSON values without using a struct?

polaris · · 474 次点击    
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
<p>One of my other projects is to create a linux binary that will interface with an API. I&#39;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&#39;m trying to cover and I don&#39;t want to build models for all of them because they could also change over time and require maintenance.</p> <p>So i&#39;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, &amp;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&#39;s cool. i will take a look at that and plat around with it. Thanks again!</p></pre>skarlso: <pre><p>You&#39;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&#39;s really tabular data so I can print it out in columns and print an individual row if needed. Since it&#39;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&#39;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&#39;t need to immediately parse to a struct.</p></pre>

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

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