Javascript 如何在 HTML 页面上显示原始 JSON 数据

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14195530/
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-24 15:58:08  来源:igfitidea点击:

How to display raw JSON data on a HTML page

javascriptjqueryhtmlcssjson

提问by timon.ma

Possible Duplicate:
JSON pretty print using JavaScript

可能的重复:
使用 JavaScript 的 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:

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

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

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

它来自http://jsonview.com/,如果您使用 Chrome 并安装了 JSONView 插件,我想要实现的是 http://jsonview.com/example.json

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?

我试过,但未能理解它是如何工作的。我想使用 JS 脚本(CSS 来突出显示)来自定义格式我的原始 JSON 数据,该数据由 ajax 检索,最后将其放在 HTML 页面上的任何位置,例如放入 div 元素中。是否有任何现有的 JS 库可以实现这一目标?或者怎么做?

回答by guypursey

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

我认为在 HTML 页面上显示数据所需的只是JSON.stringify.

For example, if your JSON is stored like this:

例如,如果您的 JSON 存储如下:

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

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

然后你只需要这样做就可以将其转换为字符串:

var jsonStr = JSON.stringify(jsonVar);

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

然后你可以直接插入到你的 HTML 中,例如:

document.body.innerHTML = jsonStr;

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

当然,您可能希望body通过getElementById.

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.

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

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

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 spaceargument of 'JSON.stringify'). But you could this as a basis for different types of formatting.

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

回答by Rui Vieira

Note that the link you provided does is not an HTML page, but rather a JSON document. The formatting is done by the browser.

请注意,您提供的链接不是 HTML 页面,而是 JSON 文档。格式化由浏览器完成。

You have to decide if:

您必须决定是否:

  1. You want to show the raw JSON (not an HTML page), as in your example
  2. Show an HTML page with formatted JSON
  1. 您想显示原始 JSON(不是 HTML 页面),如您的示例所示
  2. 显示带有格式化 JSON 的 HTML 页面

If you want 1., just tell your application to render a response body with the JSON, set the MIME type (application/json), etc. In this case, formatting is dealt by the browser (and/or browser plugins)

如果您想要 1.,只需告诉您的应用程序使用 JSON 呈现响应正文,设置 MIME 类型(应用程序/json)等。在这种情况下,格式由浏览器(和/或浏览器插件)处理

If 2., it's a matter of rendering a simple minimal HTML page with the JSON where you can highlight it in several ways:

如果是 2.,则需要使用 JSON 呈现一个简单的最小 HTML 页面,您可以在其中以多种方式突出显示它:

  • server-side, depending on your stack. There are solutions for almost every language
  • client-side with Javascript highlight libraries.
  • 服务器端,取决于您的堆栈。几乎每种语言都有解决方案
  • 带有 Javascript 高亮库的客户端。

If you give more details about your stack, it's easier to provide examples or resources.

如果您提供有关堆栈的更多详细信息,则提供示例或资源会更容易。

EDIT: For client side JS highlighting you can try higlight.js, for instance.

编辑:对于客户端JS彰显你可以尝试higlight.js,例如。

回答by Saeed Neamati

JSON in any HTML tag except <script>tag would be a mere text. Thus it's like you add a story to your HTML page.

除了 tag 之外的任何 HTML 标签中的 JSON<script>都只是一个文本。因此,这就像您向 HTML 页面添加故事一样。

However, about formatting, that's another matter. I guess you should change the title of your question.

但是,关于格式,那是另一回事。我想你应该改变你的问题的标题。

Take a look at thisquestion. Also see thispage.

看看这个问题。另请参阅页面。