Handling malformed JSON in PHP

前端 未结 5 786
时光取名叫无心
时光取名叫无心 2021-01-12 01:58

I\'m trying to write a php script that handles data from a webservice that delivers \"json\" as a string. The problem is the string isn\'t really json; it\'s javascript. Spe

相关标签:
5条回答
  • 2021-01-12 02:30

    Ok. try to use this. http://pear.php.net/pepr/pepr-proposal-show.php?id=198 I just check your string

    0 讨论(0)
  • 2021-01-12 02:30

    Depends on how complicated your data is :

    $output = "{desc:'User defined payload',asc:'whatever'}";
    
    function json_js_php($string){
    
        $string = str_replace("{",'{"',$string);
        $string = str_replace(":'",'":"',$string);
        $string = str_replace("',",'","',$string);
        $string = str_replace("'}",'"}',$string);
        return $string;
    
    }
    
    echo json_decode(json_js_php($output))->{'desc'}; 
    

    returns : User defined payload

    0 讨论(0)
  • 2021-01-12 02:42

    If the problem is just the unquoted identifiers and the data can be assumed not to contain any curly brackets, this should do it:

    $goodJson = preg_replace("/{\s*([a-zA-Z0-9_]+)/", '{ "$1"', $badJson);
    

    (not tested!)

    0 讨论(0)
  • 2021-01-12 02:45

    Using regexp is a no-go. JSON grammar cannot be correctly parsed using regexp. You will open yourself to a ton of future bugs.

    I recommend using some kind of a YAML parser. YAML is backwards-compatible with JSON and allows unquoted literals at the same time.

    Symfony YAML component worked great for me.

    And remember that there will be a performance penalty in comparison to json_decode because it's implemented natively.

    0 讨论(0)
  • 2021-01-12 02:50

    Try this:

    $jsonString = "{result:true,username:'usr000242',password:'123456',message:'Cannot send username and password to email@test.com'}";
    function manualFixInvalidJSON($jsonString=''){
        $jsonString = preg_replace("/([{,])([a-zA-Z][^: ]+):/", "\$1\"$2\":", $jsonString);
        $jsonString = preg_replace("/:([a-zA-Z\'][^:]+)([,}])/", ":\"$1\"$2", $jsonString);
        $jsonString = json_decode($jsonString,true);
        function trimer($val){
            return trim(trim($val,"'"),"\"");
        }
        $jsonString = array_map('trimer', $jsonString);
        return json_encode($jsonString);
    }
    echo jsonString($jsonString);
    
    0 讨论(0)
提交回复
热议问题