How to render json with arbitrary keys using mustache?
I have a JSON object that looks like the following:
{
"XXX":{"name":"First"},
"YYY":{"name":"Second"},
....
}
I need to render it to look like:
<div>
<h1>XXX</h1>
<p>First</p>
</div>
<div>
<h1>YYY</h1>
<p>Second</p&g开发者_如何学运维t;
</div>
....
How will I accomplish this using Mustache? The problem I am facing is that I don't know how to reference the items because the key names are arbitrary.
Convert the JSON to a hash using your favorite JSON parser, that will give you something that looks like this:
json = {
"XXX" => {"name" => "First"},
"YYY" => {"name" => "Second"},
"ZZZ" => {"name" => "Third"}
}
Then simply rearrange it into a list of little hashes with known keys:
for_mustache = json.keys.inject([ ]) do |a, k|
a.push({ :k => k, :v => json[k]['name']})
a
end
There are probably cleverer ways to do that above. Now you'll have something simple and regular like this in for_mustache
:
[
{ :k => "XXX", :v => "First" },
{ :k => "YYY", :v => "Second" },
{ :k => "ZZZ", :v => "Third" }
]
Then you can handle that data structure just like any other array of hashes in Mustache:
{{#for_mustache}}
<div>
<h1>{{k}}</h1>
<p>{{v}}</p>
</div>
{{/for_mustache}}
精彩评论