Render complex JSON with mustache.js

自闭症网瘾萝莉.ら 提交于 2019-12-08 12:46:21

问题


I am a newbie on CouchDB. I was familiar with JSON from quiet sometime. My problem now is a I have a pretty complex JSON data. I also read some of the documentation of mustache.js and felt it was very apt to render JSON. It's fine for rendering simple JSON, but how do I do if there exists nested objects. Below is my sample JSON:

{
 "name": "John",
 "email": "john@abc.com",
 "files": {
         "img1.jpg":
               {"content_type": "image/jpeg", "revpos": 3, "length": 33423, "stub": true},
         "img2.jpg": 
              {"content_type": "image/jpeg", "revpos": 2, "length": 146909, "stub": true}
 }

}

I would like to display my name, email and the image file. How do I accomplish this using mustache.js


回答1:


I would change how your data returns.

{
 "name": "John",
 "email": "john@abc.com",
 "files": {
         0:
               {"filename": "image1.jpg", "content_type": "image/jpeg", "revpos": 3, "length": 33423, "stub": true},
         1: 
              {"filename": "image2.jpg", "content_type": "image/jpeg", "revpos": 2, "length": 146909, "stub": true}
 }

Your output should be like this:

Name: {{name}}<br />
Email: {{email}}<br />
Files: <ul>
{{#.}}
    <li>{{filename}}</li>
{{/.}}
</ul>



回答2:


I don't know how to loop an object and get it's key but if you add a "filename" property to the files you could do it like this:

Name: {{name}}<br />
Email: {{email}}<br />
Files: <ul>
{{#files}}
    <li>{{filename}}</li>
{{/files}}
</ul>

https://github.com/janl/mustache.js#non-empty-lists

BTW: What you posted is valid JS but not valid JSON (the quotation marks around the keys are missing)



来源:https://stackoverflow.com/questions/11611522/render-complex-json-with-mustache-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!