如何在HTML页面上显示原始JSON数据 [英] How to display raw JSON data on a HTML page

查看:169
本文介绍了如何在HTML页面上显示原始JSON数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
使用JavaScript的JSON漂亮打印

Possible Duplicate:
JSON pretty print using JavaScript

我想像JSONview一样在HTML页面上显示我的原始JSON数据.例如,我的原始json数据是:

I'd like to display my raw JSON data on a HTML page just as JSONview does. For example, my raw json data is:

  {
   "hey":"guy",
   "anumber":243,
   "anobject":{
      "whoa":"nuts",
      "anarray":[
         1,
         2,
         "thr<h1>ee"
      ],
      "more":"stuff"
   },
   "awesome":true,
   "bogus":false,
   "meaning":null,
   "japanese":"明日がある。",
   "link":"http://jsonview.com",
   "notLink":"http://jsonview.com is great"
}

它来自 http://jsonview.com/,而我想要实现的效果就像 http://jsonview.com/example.json (如果您使用Chrome浏览器并已安装JSONView插件).

It comes from http://jsonview.com/, and what I want to achieve is like http://jsonview.com/example.json if you use Chrome and have installed the JSONView plugin.

我已经尝试过,但是无法理解它是如何工作的.我想使用JS脚本(突出显示CSS)来格式化我的原始JSON数据,该数据由ajax检索,最后将其放在HTML页面上的任何位置,例如放入div元素中.有没有现成的JS库可以实现这一目标?还是怎么做?

I've tried but failed to understand how it works. I'd like to use a JS script (CSS to highlight) to custom format my raw JSON data which is retrieved by ajax and finally put it on a HTML page in any position like into a div element. Are there any existing JS libraries that can achieve this? Or how to do it?

推荐答案

我认为您只需在

I think all you need to display the data on an HTML page is JSON.stringify.

例如,如果您的JSON是这样存储的:

For example, if your JSON is stored like this:

var jsonVar = {
        text: "example",
        number: 1
    };

然后您只需要执行以下操作即可将其转换为字符串:

Then you need only do this to convert it to a string:

var jsonStr = JSON.stringify(jsonVar);

然后您可以直接插入HTML中,例如:

And then you can insert into your HTML directly, for example:

document.body.innerHTML = jsonStr;

当然,您可能希望通过getElementByIdbody替换为其他元素.

Of course you will probably want to replace body with some other element via getElementById.

对于问题的CSS部分,可以在将字符串化对象放入DOM之前使用RegExp对其进行操作.例如,此代码(也在JSFiddle上用于演示目的)应注意花括号的缩进.

As for the CSS part of your question, you could use RegExp to manipulate the stringified object before you put it into the DOM. For example, this code (also on JSFiddle for demonstration purposes) should take care of indenting of curly braces.

var jsonVar = {
        text: "example",
        number: 1,
        obj: {
            "more text": "another example"
        },
        obj2: {
             "yet more text": "yet another example"
        }
    }, // THE RAW OBJECT
    jsonStr = JSON.stringify(jsonVar),  // THE OBJECT STRINGIFIED
    regeStr = '', // A EMPTY STRING TO EVENTUALLY HOLD THE FORMATTED STRINGIFIED OBJECT
    f = {
            brace: 0
        }; // AN OBJECT FOR TRACKING INCREMENTS/DECREMENTS,
           // IN PARTICULAR CURLY BRACES (OTHER PROPERTIES COULD BE ADDED)

regeStr = jsonStr.replace(/({|}[,]*|[^{}:]+:[^{}:,]*[,{]*)/g, function (m, p1) {
var rtnFn = function() {
        return '<div style="text-indent: ' + (f['brace'] * 20) + 'px;">' + p1 + '</div>';
    },
    rtnStr = 0;
    if (p1.lastIndexOf('{') === (p1.length - 1)) {
        rtnStr = rtnFn();
        f['brace'] += 1;
    } else if (p1.indexOf('}') === 0) {
         f['brace'] -= 1;
        rtnStr = rtnFn();
    } else {
        rtnStr = rtnFn();
    }
    return rtnStr;
});

document.body.innerHTML += regeStr; // appends the result to the body of the HTML document

此代码只是在字符串中查找对象的各个部分,并将它们分成div(尽管您可以更改其中的HTML部分).但是,每次遇到大括号时,都会根据开括号或闭括号来增加或减少缩进(行为类似于JSON.stringify"的 space 参数).但是您可以以此为基础来设置不同类型的格式.

This code simply looks for sections of the object within the string and separates them into divs (though you could change the HTML part of that). Every time it encounters a curly brace, however, it increments or decrements the indentation depending on whether it's an opening brace or a closing (behaviour similar to the space argument of 'JSON.stringify'). But you could this as a basis for different types of formatting.

这篇关于如何在HTML页面上显示原始JSON数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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