Search code examples
phpcurldoublequotes

Convert string (similar json format) to object or array


I receive string "{success: false, errors: { reason: 'text text text' }}" by CURL, how to convert this string to array or object?

String '{"success": "false"....}' may be converted to object by json_decode, but I have string without qoutes.


Solution

  • Use this regex first (it adds quotes)

    $json = preg_replace ('/(?<!")(?<!\w)(\w+)(?!")(?!\w)/u', '"$1"', $string);
    

    After that, you can simply use json_decode()

    $array = json_decode ($json);
    

    Update

    I found this script somewhere:

    function json_fix_quotes ($string){
        $string = str_replace("{",'{"',$string);
        $string = str_replace(":'",'":"',$string);
        $string = str_replace("',",'","',$string);
        $string = str_replace("'}",'"}',$string);
        return $string;
    }
    

    Try that instead of the regex