Javascript 从 JSON 自动生成 HTML

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5710798/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 18:33:42  来源:igfitidea点击:

Automatically generate HTML from JSON

javascripthtmljsontemplates

提问by Mikkel

I am working on a template system. I imagine that as a regular user you can create a. json file, and based on that file the system will automatically generate html. I am fairly lost with how to approach it. Maybe I could create a recursive loop that runs through all objects and then.... (well I'm lost).

我正在研究模板系统。我想作为普通用户,您可以创建一个。json 文件,系统将根据该文件自动生成 html。我对如何接近它感到相当迷茫。也许我可以创建一个遍历所有对象的递归循环,然后......(好吧我迷路了)。

An example of how the JSON could look: http://pastebin.com/cJ376fiF.

JSON 外观示例:http: //pastebin.com/cJ376fiF

How the generated HTML should look like: http://pastebin.com/e4EytHm1.

生成的 HTML 应如下所示:http: //pastebin.com/e4EytHm1

回答by Bernicc

http://www.json2html.com/

http://www.json2html.com/

"json2html is an open source jQuery plug-in that relies on JSON transforms to convert JSON objects to HTML."

“json2html 是一个开源 jQuery 插件,它依赖 JSON 转换将 JSON 对象转换为 HTML。”

回答by topherg

probably a bit late, i was gonna do something similar, and came across this thread, but have some code, the callback function is called from an XHR object which gets data from the currently static file "response.json"

可能有点晚了,我想做类似的事情,遇到了这个线程,但是有一些代码,回调函数是从 XHR 对象调用的,该对象从当前静态文件“response.json”中获取数据

function callback(req)
{
    var response = eval("("+req.responseText+")");
    response = response.response;

    createElementsFromJSON(response, document.body);
}

function createElementsFromJSON(json, parent)
{
    for(var i in json)
    {
        var object = json[i];

        var obj = document.createElement(object.element);

        for(var tag in object)
            if (tag!="children"&&tag!="element")
                obj.setAttribute(tag, object[tag]);

        parent.appendChild(obj);

        if (typeof(object.children)=="object")
            createElementsFromJSON(object.children, obj);
    }
}

JSON:

JSON:

{
    "response":
    [
        {
            "element":"div",
            "id":"james",
            "children":
            [
                {
                    "element":"h1",
                    "id":"bob",
                    "innerHTML":"bobs content",
                },
                {
                    "element":"h2",
                    "id":"rob",
                    "innerHTML":"robs content",
                },
                {
                    "element":"p",
                    "innerHTML":"some random text",
                },
            ],
        },
        {
            "element":"div",
            "id":"alex",
            "innerHTML":"this is a test message in a div box",
        },
    ]
}

回答by Marcus

jQote2 is an excellent javascript templating plugin, which should be atleast a good benchmark. It parses JSON into HTML templates in a very handy way. http://aefxx.com/jquery-plugins/jqote2/

jQote2 是一个优秀的 javascript 模板插件,至少应该是一个很好的基准测试。它以一种非常方便的方式将 JSON 解析为 HTML 模板。 http://aefxx.com/jquery-plugins/jqote2/

回答by Krishnakumar_Muraleedharan

I have done a humble attempt for my own project to dynamically generate html content through JSON. You can try the fiddlehere. You are welcome to fork it since the JSON format is different.

我为自己的项目做了一个简单的尝试,通过 JSON 动态生成 html 内容。你可以试试这里的小提琴。由于 JSON 格式不同,欢迎您 fork。

Sample JSON format would look as below.

示例 JSON 格式如下所示。

var innerhtml = {
  type: 'b',
  content: ['This is BOLD text.', {
    type: 'i',
    content: ' Italics came from Italy? Its 35px and bold too.',
    style: 'font-size:35px;'
  }]
};

var htmlArr = {
  type: 'div',
  content: {
    type: 'p',
    content: ['Simple text with no formatting.', innerhtml, {type : 'img', src : '//www.gravatar.com/avatar/476914f28548ce41b3b7b2c5987720a9/?default=&s=64'}]
  }

};

回答by B.F.

@topherg

@topherg

  • It is faster to bind obj to parent earlier - direct after createElement.

  • When you come to object.children you should check:

    if(object.children.constructor===Array){
      for(var i=0;i<object.children.length;i++)
         createElementsFromJSON(object.children[i],obj);
    }else{
       createElementsFromJSON(object.children,obj);
    }
    

    Otherwise no array will be parsed.

  • SetAttribute is slow but sometimes you need it for (name,item*,data-*,rel,objekt,param,loop,datetime,style[if you don't want to parse an additional object],colspan,...). Direct Set Attribute (element.style.width="100px";) is 88 times faster (jsPerf).
  • 更早地将 obj 绑定到父级更快 - 直接在 createElement 之后。

  • 当你来到 object.children 你应该检查:

    if(object.children.constructor===Array){
      for(var i=0;i<object.children.length;i++)
         createElementsFromJSON(object.children[i],obj);
    }else{
       createElementsFromJSON(object.children,obj);
    }
    

    否则不会解析任何数组。

  • SetAttribute 很慢但有时你需要它 (name,item*,data-*,rel,objekt,param,loop,datetime,style[如果你不想解析额外的对象],colspan,...) . 直接设置属性 (element.style.width="100px";) 快 88 倍 ( jsPerf)。

To create ONE DOM element is faster than innerHTML. Building a DOM tree directly, takes double time of innerHTML. Even innerHTML is very fast that kind of DOM parsing is still fast too.

创建一个 DOM 元素比innerHTML 快。直接构建 DOM 树需要两倍于innerHTML的时间。即使innerHTML 非常快,那种DOM 解析也仍然很快。