如何使用胡须使用任意键渲染JSON? [英] How to render json with arbitrary keys using mustache?

查看:59
本文介绍了如何使用胡须使用任意键渲染JSON?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类似于以下内容的JSON对象:

I have a JSON object that looks like the following:

{
    "XXX":{"name":"First"},
    "YYY":{"name":"Second"},
    ....
}

我需要将其呈现为:

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

推荐答案

使用您喜欢的JSON解析器将JSON转换为哈希,这将为您提供类似于以下的内容:

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

上面可能有更聪明的方法来做到这一点.现在,您将在for_mustache中拥有一些简单而又常规的内容:

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

然后,您可以像处理Mustache中的其他任何哈希数组一样处理该数据结构:

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

这篇关于如何使用胡须使用任意键渲染JSON?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆