pretty-print JSON using JavaScript

后端 未结 24 1679
一向
一向 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

提交回复
热议问题