pretty-print JSON using JavaScript

后端 未结 24 1722
一向
一向 2020-11-21 06:45

How can I display JSON in an easy-to-read (for human readers) format? I\'m looking primarily for indentation and whitespace, with perhaps even colors / font-styles / etc.

相关标签:
24条回答
  • 2020-11-21 07:16

    I ran into an issue today with @Pumbaa80's code. I'm trying to apply JSON syntax highlighting to data that I'm rendering in a Mithril view, so I need to create DOM nodes for everything in the JSON.stringify output.

    I split the really long regex into its component parts as well.

    render_json = (data) ->
      # wraps JSON data in span elements so that syntax highlighting may be
      # applied. Should be placed in a `whitespace: pre` context
      if typeof(data) isnt 'string'
        data = JSON.stringify(data, undefined, 2)
      unicode =     /"(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?/
      keyword =     /\b(true|false|null)\b/
      whitespace =  /\s+/
      punctuation = /[,.}{\[\]]/
      number =      /-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/
    
      syntax = '(' + [unicode, keyword, whitespace,
                punctuation, number].map((r) -> r.source).join('|') + ')'
      parser = new RegExp(syntax, 'g')
    
      nodes = data.match(parser) ? []
      select_class = (node) ->
        if punctuation.test(node)
          return 'punctuation'
        if /^\s+$/.test(node)
          return 'whitespace'
        if /^\"/.test(node)
          if /:$/.test(node)
            return 'key'
          return 'string'
    
        if /true|false/.test(node)
          return 'boolean'
    
         if /null/.test(node)
           return 'null'
         return 'number'
      return nodes.map (node) ->
        cls = select_class(node)
        return Mithril('span', {class: cls}, node)
    

    Code in context on Github here

    0 讨论(0)
  • 2020-11-21 07:17

    Couldn't find any solution that had good syntax highlighting for the console, so here's my 2p

    Install & Add cli-highlight dependency

    npm install cli-highlight --save
    

    Define logjson globally

    const highlight = require('cli-highlight').highlight
    console.logjson = (obj) => console.log(
                                   highlight( JSON.stringify(obj, null, 4), 
                                              { language: 'json', ignoreIllegals: true } ));
    

    Use

    console.logjson({foo: "bar", someArray: ["string1", "string2"]});
    

    0 讨论(0)
  • 2020-11-21 07:18

    I use the JSONView Chrome extension (it is as pretty as it gets :):

    Edit: added jsonreport.js

    I've also released an online stand-alone JSON pretty print viewer, jsonreport.js, that provides a human readable HTML5 report you can use to view any JSON data.

    You can read more about the format in New JavaScript HTML5 Report Format.

    0 讨论(0)
  • 2020-11-21 07:18

    To highlight and beautify it in HTML using Bootstrap:

    function prettifyJson(json, prettify) {
        if (typeof json !== 'string') {
            if (prettify) {
                json = JSON.stringify(json, undefined, 4);
            } else {
                json = JSON.stringify(json);
            }
        }
        return json.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g,
            function(match) {
                let cls = "<span>";
                if (/^"/.test(match)) {
                    if (/:$/.test(match)) {
                        cls = "<span class='text-danger'>";
                    } else {
                        cls = "<span>";
                    }
                } else if (/true|false/.test(match)) {
                    cls = "<span class='text-primary'>";
                } else if (/null/.test(match)) {
                    cls = "<span class='text-info'>";
                }
                return cls + match + "</span>";
            }
        );
    }
    
    0 讨论(0)
  • 2020-11-21 07:20

    You can use JSON.stringify(your object, null, 2) The second parameter can be used as a replacer function which takes key and Val as parameters.This can be used in case you want to modify something within your JSON object.

    more reference : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify

    0 讨论(0)
  • 2020-11-21 07:21

    This is nice:

    https://github.com/mafintosh/json-markup from mafintosh

    const jsonMarkup = require('json-markup')
    const html = jsonMarkup({hello:'world'})
    document.querySelector('#myElem').innerHTML = html
    

    HTML

    <link ref="stylesheet" href="style.css">
    <div id="myElem></div>
    

    Example stylesheet can be found here

    https://raw.githubusercontent.com/mafintosh/json-markup/master/style.css
    
    0 讨论(0)
提交回复
热议问题