Need help sending JSON response to front end

blov · · 364 次点击    
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
<p>Hi, Using the net/http package I created a server with an endpoint that will perform a calculation and return an array of arrays[8][8]int. What is the easiest way to send this back to the front end as a json array of arrays? </p> <hr/>**评论:**<br/><br/>dcowboy: <pre><p><a href="https://play.golang.org/p/DaKDivWGkK" rel="nofollow">https://play.golang.org/p/DaKDivWGkK</a></p> <p>The basic gist is that you want to create a custom type to hold your response. Create an instance of that type, populate it with your data, and then use json.Marshal to convert it into a JSON string which can be returned to your front end.</p></pre>nickelstheclown: <pre><p>Thanks a lot I will try that. I guess I was hoping there was an easy method I could just call on my array to turn it into a json array, but this seems doable.</p></pre>titpetric: <pre><p>You can just Marshal ro.Response and you&#39;ll get an array directly (no enclosing object). Is that what you wanted?</p></pre>Redundancy_: <pre><p>I&#39;m not sure if that would (should?) work. I remember there being security issues with un-contained arrays.</p></pre>titpetric: <pre><p>It does if just to modify the go playground example :)</p></pre>Morgahl: <pre><p><a href="https://play.golang.org/p/00rFcDLHP-" rel="nofollow">https://play.golang.org/p/00rFcDLHP-</a></p> <p>Functioning example :)</p></pre>dcowboy: <pre><p>That was my first iteration of what I ultimately posted, but it seemed bad form to not return a proper JSON object contained in { }. Not sure if it makes any difference depending on what front end library he is using.</p></pre>Morgahl: <pre><p>At that point it does seem to be a matter of preference with no correct answers just strong opinions.</p> <p>I personally like full objects myself as they are a bit more explicit and if APIs I write ever get consumed by 3rd party code bases it provides an implicit contract of functionality. But if I got a design doc requesting a return in this manner I would not really think twice about it.</p> <p>Happy coding!</p></pre>Redundancy_: <pre><p><a href="https://stackoverflow.com/questions/3503102/what-are-top-level-json-arrays-and-why-are-they-a-security-risk" rel="nofollow">https://stackoverflow.com/questions/3503102/what-are-top-level-json-arrays-and-why-are-they-a-security-risk</a></p> <p>Not entirely sure if still relevant, but worth being aware of?</p></pre>rbsns: <pre><p>why not <a href="https://play.golang.org/p/JiZkOpHkgK" rel="nofollow">https://play.golang.org/p/JiZkOpHkgK</a> ?</p></pre>

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

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