How to render json with arbitrary keys using mustache?

白昼怎懂夜的黑 提交于 2020-01-03 01:40:24

问题


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>
</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.


回答1:


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}}


来源:https://stackoverflow.com/questions/5565948/how-to-render-json-with-arbitrary-keys-using-mustache

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