问题
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