Regex to validate JSON

前端 未结 12 2393
挽巷
挽巷 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条回答
  •  Happy的楠姐
    2020-11-22 11:46

    I tried @mario's answer, but it didn't work for me, because I've downloaded test suite from JSON.org (archive) and there were 4 failed tests (fail1.json, fail18.json, fail25.json, fail27.json).

    I've investigated the errors and found out, that fail1.json is actually correct (according to manual's note and RFC-7159 valid string is also a valid JSON). File fail18.json was not the case either, cause it contains actually correct deeply-nested JSON:

    [[[[[[[[[[[[[[[[[[[["Too deep"]]]]]]]]]]]]]]]]]]]]
    

    So two files left: fail25.json and fail27.json:

    ["  tab character   in  string  "]
    

    and

    ["line
    break"]
    

    Both contains invalid characters. So I've updated the pattern like this (string subpattern updated):

    $pcreRegex = '/
              (?(DEFINE)
                 (?   -? (?= [1-9]|0(?!\d) ) \d+ (\.\d+)? ([eE] [+-]? \d+)? )
                 (?   true | false | null )
                 (?    " ([^"\n\r\t\\\\]* | \\\\ ["\\\\bfnrt\/] | \\\\ u [0-9a-f]{4} )* " )
                 (?     \[  (?:  (?&json)  (?: , (?&json)  )*  )?  \s* \] )
                 (?      \s* (?&string) \s* : (?&json)  )
                 (?    \{  (?:  (?&pair)  (?: , (?&pair)  )*  )?  \s* \} )
                 (?   \s* (?: (?&number) | (?&boolean) | (?&string) | (?&array) | (?&object) ) \s* )
              )
              \A (?&json) \Z
              /six';
    
    
    

    So now all legal tests from json.org can be passed.

    提交回复
    热议问题