简体   繁体   English

漂亮的JSON格式

[英]Pretty format JSON

I want to put <span> around some numbers in pretty-printed JSON output. 我想在漂亮打印的JSON输出中将<span>放在一些数字周围。

I am using JSON.stringify() with a replacer to do this. 我使用JSON.stringify()替代品来做到这一点。 However, as the returned type of an HTML fragment with a span in is a string, these now get quoted. 但是,由于返回的跨度为HTML片段的类型是字符串,因此现在将其引号。

How can I put spans around numbers? 我该如何在数字周围加跨度?

An example: 一个例子:

JSON.stringify(
    {
        with_span:1,
        without_span:1
    },
    function(key,value) {
        if(key=="with_span")
            return '<span>'+value+'</span>'; // but I don't want this quoted! :(
        return value;
    },
    4) // the indent

outputs: 输出:

{
    "with_span": "1",
    "without_span": 1
}

json2 (公共领域-未获得版权)中获取stringify()函数,并将其修改为输出格式化的HTML。

It's not possible with JSON.stringify() . JSON.stringify()不可能的。

JSON.stringify() will return a valid JSON string, and Without the quotes it is not a valid json string. JSON.stringify()将返回有效的JSON字符串,并且如果没有引号,则它不是有效的json字符串。

To achieve what you want, you have to traverse the object yourself and render it as HTML. 为了实现所需的功能,您必须自己遍历对象并将其呈现为HTML。

I don't know your use case, but maybe you could just use a library to do the work? 我不知道您的用例,但也许您可以只使用一个库来完成工作? For example google-code-prettify . 例如google-code-prettify

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM