Regex to validate JSON

前端 未结 12 2383
挽巷
挽巷 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

    As was written above, if the language you use has a JSON-library coming with it, use it to try decoding the string and catch the exception/error if it fails! If the language does not (just had such a case with FreeMarker) the following regex could at least provide some very basic validation (it's written for PHP/PCRE to be testable/usable for more users). It's not as foolproof as the accepted solution, but also not that scary =):

    ~^\{\s*\".*\}$|^\[\n?\{\s*\".*\}\n?\]$~s
    

    short explanation:

    // we have two possibilities in case the string is JSON
    // 1. the string passed is "just" a JSON object, e.g. {"item": [], "anotheritem": "content"}
    // this can be matched by the following regex which makes sure there is at least a {" at the
    // beginning of the string and a } at the end of the string, whatever is inbetween is not checked!
    
    ^\{\s*\".*\}$
    
    // OR (character "|" in the regex pattern)
    // 2. the string passed is a JSON array, e.g. [{"item": "value"}, {"item": "value"}]
    // which would be matched by the second part of the pattern above
    
    ^\[\n?\{\s*\".*\}\n?\]$
    
    // the s modifier is used to make "." also match newline characters (can happen in prettyfied JSON)
    

    if I missed something that would break this unintentionally, I'm grateful for comments!

提交回复
热议问题