skip to Main Content

I have a string of json objects I need to json_decode but the json format is not valid because it doesn’t have double quotes (or any quote). And some texts have commas what makes it more difficult to format as json.

This is the string I get:

[{2:,0:1,1:Rodapiu00e9s 1-a, 2-a, bloque 6}]

This is the format I need to be a valid JSON:

[{"2":"","0":"1","1":"Rodapiu00e9s 1-a, 2-a, bloque 6"}]

I have a code to add strings but doesn’t work with texts containing commas:

$str = str_replace('{', '{"', $str);
$str = str_replace(':', '":"', $str);
$str = str_replace(',', '","', $str);
$str = str_replace('}', '"}', $str);
$str = str_replace('}","{', '},{', $str);

This is what I get:

[{"2":"","0":"1","1":"Rodapiu00e9s 1-a"," 2-a"," bloque 6"}]

2

Answers


  1. Replace numeric keys with string keys

    $str = preg_replace('/(d+):/', '"$1":', $str);
    

    Add double quotes around values

    $str = preg_replace('/(":)(.*?)(,"|})/', '$1"$2"$3', $str);
    
    Login or Signup to reply.
  2. If your keys are numeric, then the following regex should meet your needs:

    (?<=[{,])s*(d+)s*:(.*?)(?=}|,s*d+s*:)
    

    It matches:

    • (?<=[{,]) : lookbehind for { or ,
    • s*(d+)s*: : a numeric key, possibly surrounded by spaces, captured in group 1
    • (.*?) : a minimal number of characters, captured in group 2, subject to the following lookahead
    • (?=}|,s*d+s*:) : a lookahead for either a } or a comma followed by a numeric key value

    Demo on regex101

    In PHP:

    $str = '[{2:,0:1,1:Rodapiu00e9s 1-a, 2-a, bloque 6},
    {4:x, y, z,0 :111, 3:some random text},{5:a45:bc,def}]';
    
    $str = preg_replace('/(?<=[{,])s*(d+)s*:(.*?)(?=}|,s*d+s*:)/', '"$1":"$2"', $str);
    
    $obj = json_decode($str);
    print_r($obj);
    

    Output:

    Array
    (
        [0] => stdClass Object
            (
                [2] => 
                [0] => 1
                [1] => Rodapiés 1-a, 2-a, bloque 6
            )
        [1] => stdClass Object
            (
                [4] => x, y, z
                [0] => 111
                [3] => some random text
            )
        [2] => stdClass Object
            (
                [5] => a45:bc,def
            )
    )
    

    Demo on 3v4l.org

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search