Regex to validate JSON

前端 未结 12 2385
挽巷
挽巷 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:57

    Looking at the documentation for JSON, it seems that the regex can simply be three parts if the goal is just to check for fitness:

    1. The string starts and ends with either [] or {}
      • [{\[]{1}...[}\]]{1}
    2. and
      1. The character is an allowed JSON control character (just one)
        • ...[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]...
      2. or The set of characters contained in a ""
        • ...".*?"...

    All together: [{\[]{1}([,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]|".*?")+[}\]]{1}

    If the JSON string contains newline characters, then you should use the singleline switch on your regex flavor so that . matches newline. Please note that this will not fail on all bad JSON, but it will fail if the basic JSON structure is invalid, which is a straight-forward way to do a basic sanity validation before passing it to a parser.

提交回复
热议问题