Question

My json files has comments in it like this

{
    // Texts
    "txtloggedas": "U bent aangemeld als",
    "txtlogin": "Aanmelden",

How can I delete the rule // Texts with php code? (for all comments in my file). Because the json is not valid.

Was it helpful?

Solution

Also you can try this:

<?php
 $file = "test.json";
 $str = file_get_contents($file);
 while(strpos($str,'//')){ //---- while in text exist // do ----
  $a = strpos($str,'//'); //---- first position // ----
  $b = strpos($str,'"',$a); //--- first position of " in text ---
  if($b==0) {$b = strpos($str,'}',$a);} //--- if // at end of file  ---

  $s1 = substr($str,0,$a); //---- new string from start to // position ---
  $s2 = substr($str,$b); //--- string from first " to end of file ---

  $str = $s1.$s2; //---- new string without // ----
 }
 file_put_contents($file,$str); 
?>

OTHER TIPS

Generally preg_match is a great function for checking for characters, in your example you'd have to check for //. Assuming your JSON is saved in a file somewhere, maybe this code snippet could help you:

<?php
$rows = file("json.txt");    

foreach($rows as $key => $row) {
    if(preg_match("/\/\//", $row)) {
        unset($rows[$key]);
    }
}

file_put_contents("fixedjson.txt", implode($rows));

?>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top