简体   繁体   中英

Pretty format JSON

I want to put <span> around some numbers in pretty-printed JSON output.

I am using JSON.stringify() with a replacer to do this. However, as the returned type of an HTML fragment with a span in is a string, these now get quoted.

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() will return a valid JSON string, and Without the quotes it is not a valid json string.

To achieve what you want, you have to traverse the object yourself and render it as 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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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