Regex to validate JSON

前端 未结 12 2518
挽巷
挽巷 2020-11-22 11:37

I am looking for a Regex that allows me to validate json.

I am very new to Regex\'s and i know enough that parsing with Regex is bad but can it be used to validate?

12条回答
  •  忘掉有多难
    2020-11-22 11:50

    I created a Ruby implementation of Mario's solution, which does work:

    # encoding: utf-8
    
    module Constants
      JSON_VALIDATOR_RE = /(
             # define subtypes and build up the json syntax, BNF-grammar-style
             # The {0} is a hack to simply define them as named groups here but not match on them yet
             # I added some atomic grouping to prevent catastrophic backtracking on invalid inputs
             (?  -?(?=[1-9]|0(?!\d))\d+(\.\d+)?([eE][+-]?\d+)?){0}
             (? true | false | null ){0}
             (?  " (?>[^"\\\\]* | \\\\ ["\\\\bfnrt\/] | \\\\ u [0-9a-f]{4} )* " ){0}
             (?   \[ (?> \g (?: , \g )* )? \s* \] ){0}
             (?    \s* \g \s* : \g ){0}
             (?  \{ (?> \g (?: , \g )* )? \s* \} ){0}
             (?    \s* (?> \g | \g | \g | \g | \g ) \s* ){0}
           )
        \A \g \Z
        /uix
    end
    
    ########## inline test running
    if __FILE__==$PROGRAM_NAME
    
      # support
      class String
        def unindent
          gsub(/^#{scan(/^(?!\n)\s*/).min_by{|l|l.length}}/u, "")
        end
      end
    
      require 'test/unit' unless defined? Test::Unit
      class JsonValidationTest < Test::Unit::TestCase
        include Constants
    
        def setup
    
        end
    
        def test_json_validator_simple_string
          assert_not_nil %s[ {"somedata": 5 }].match(JSON_VALIDATOR_RE)
        end
    
        def test_json_validator_deep_string
          long_json = <<-JSON.unindent
          {
              "glossary": {
                  "title": "example glossary",
              "GlossDiv": {
                      "id": 1918723,
                      "boolean": true,
                      "title": "S",
                "GlossList": {
                          "GlossEntry": {
                              "ID": "SGML",
                    "SortAs": "SGML",
                    "GlossTerm": "Standard Generalized Markup Language",
                    "Acronym": "SGML",
                    "Abbrev": "ISO 8879:1986",
                    "GlossDef": {
                                  "para": "A meta-markup language, used to create markup languages such as DocBook.",
                      "GlossSeeAlso": ["GML", "XML"]
                              },
                    "GlossSee": "markup"
                          }
                      }
                  }
              }
          }
          JSON
    
          assert_not_nil long_json.match(JSON_VALIDATOR_RE)
        end
    
      end
    end
    
        

    提交回复
    热议问题