Search code examples
phpjsonbackslash

remove backslash from json string


I get bellow json string from a server response:

"\"[\n      {\n        \"id\": \"1\",\n        \"mid\": \"1\",\n        \"num\": \"1\",\n        \"type\": \"wgp\",\n        \"time_changed\": \"time\",\n        \"username\": \"aaa\"\n      }\n    ]\""

I need to reformat it to this:

"{ { "id": "1", "mid": "1", "num": "1", "type": "wgp", "time_changed": "time", "username": "aaa" } }

here is my attempt

    $str = substr($str, 2);
    $str = "{".$str;
    $str = substr($str,0, strlen($str) - 3);
    $str = $str . " }";
    $str = trim(preg_replace('/\s\s+/', ' ', $str));

it gives me

"{ { \"id\": \"1\", \"mid\": \"1\", \"num\": \"1\", \"plating_type\": \"wgp\", \"time_changed\": \"time\", \"username\": \"09122099111\" } }"

I could not remove backslashes I tried

$str= preg_replace('/\\\"/', '', $str); 
$str = str_replace('\\', '', $str);
stripslashes ()

but none of them worked


Solution

  • You can try the following way to achieve what you need,

    $jsonString = '\"[\n      {\n        \"id\": \"1\",\n        \"mid\": \"1\",\n        \"num\": \"1\",\n        \"type\": \"wgp\",\n        \"time_changed\": \"time\",\n        \"username\": \"aaa\"\n      }\n    ]\"';
    
    $jsonString = str_replace('\\n', '', $jsonString); // First remove the new line characters in the json string
    
    $jsonString = str_replace('\\', '', $jsonString); // Replace backslash with empty string
    
    echo preg_replace('!\s+!', ' ', $jsonString); // Replace multiple spaces with one
    

    So the output is,

    "[ { "id": "1", "mid": "1", "num": "1", "type": "wgp", "time_changed": "time", "username": "aaa" } ]"