Search code examples
phparraysjsonstringtext-parsing

Parse JSON string which is invalid due to missing quotes


I have a string "[[10,20],[30,40],[50,30]]" which can be converted into array by simply using json_decode which works fine for numeric values but it's failing for string values like "[S,M,L]" which I handled using a simple logic.

$string_value = str_replace(',', '","', $string_value);
$string_value = str_replace('[', '["', $string_value);
$string_value = str_replace(']', '"]', $string_value);
$string_value = json_decode($string_value);

This works fine for a one dimensional array like the one given above, but in case of a 2d array like [[red,green],[red],[red,blue]] it's failing.


Solution

  • A regex replacement would work to wrap all alphabetical characters in quotes:

    $value = preg_replace( "(\w+)", '\'$0\'', $input );
    

    Like so:

    <?php
    
    $input1 = "[[10,20],[30,40],[50,30]]";
    $input2 = "[[red,green],[red],[red,blue]]";
    
    $value1 = preg_replace( "(\w+)", '\'$0\'', $input1 );
    $value2 = preg_replace( "(\w+)", '\'$0\'', $input2 );
    
    echo $value1;
    echo "<br />";
    echo $value2;
    
    ?>
    

    Gives me this output:

    [['10','20'],['30','40'],['50','30']]
    [['red','green'],['red'],['red','blue']]