How to determine whether a string is valid JSON?

前端 未结 6 1418
自闭症患者
自闭症患者 2020-12-15 03:12

Does anyone know of a robust (and bullet proof) is_JSON function snippet for PHP? I (obviously) have a situation where I need to know if a string is JSON or not.

Hmm

6条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-15 04:00

    What about using json_decode, which should return null if the given string was not valid JSON-encoded data ?

    See example 3 on the manual page :

    // the following strings are valid JavaScript but not valid JSON
    
    // the name and value must be enclosed in double quotes
    // single quotes are not valid 
    $bad_json = "{ 'bar': 'baz' }";
    json_decode($bad_json); // null
    
    // the name must be enclosed in double quotes
    $bad_json = '{ bar: "baz" }';
    json_decode($bad_json); // null
    
    // trailing commas are not allowed
    $bad_json = '{ bar: "baz", }';
    json_decode($bad_json); // null
    

提交回复
热议问题