Search code examples
phpjsonline-breaks

Saving data across multiple lines JSON


Currently I have PHP and JS save my data in a JSON.

Below is the code for it:

PHP:

<?php

$jsonString = file_get_contents('passwords.json');
$data = json_decode($jsonString, true);
// get the q parameter from URL
$q = $_REQUEST["q"];

$item = $_REQUEST["item"];

// or if you want to change all entries with activity_code "1"
foreach ($data["passwords"] as $key => $password) {
    echo $data["passwords"][$key]['timesToUse'] - 1;
    if ($password['password'] == $q) {

        $data["passwords"][$key]['timesToUse'] = $data["passwords"][$key]['timesToUse'] - 1;
        $data["passwords"][$key]['winningItem'] = $item;
    }
}


$newJsonString = json_encode($data);
file_put_contents('passwords.json', $newJsonString);

?>

JS:

var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "passwords.php?q="+passwords[i].password+"&item="+winningItem.getFullName(), true);
xmlhttp.send();

The issue that I am having is that initially my JSON file looks like this:

{"password":"IS360H","timesToUse":1,"winningItem":""}, 
{"password":"AGRD33","timesToUse":1,"winningItem":""},
{"password":"4BX0FV","timesToUse":1,"winningItem":""}, 
{"password":"99NOTX","timesToUse":1,"winningItem":""}, 
{"password":"X2Z8BO","timesToUse":1,"winningItem":""}, 
{"password":"R9G4Q0","timesToUse":1,"winningItem":""}, 
{"password":"CG9RGT","timesToUse":1,"winningItem":""},

As you can see it is nice and neat and is sitting at 1 password per line. However once the file gets modified, it turns to this:

{"password":"IS360H","timesToUse":0,"winningItem":"counterUAV"},{"password":"AGRD33","timesToUse":0,"winningItem":"sentryGun"},"password":"4BX0FV","timesToUse":0,"winningItem":"chopperGunner"},"password":"99NOTX","timesToUse":1,"winningItem":""},{"password":"X2Z8BO","timesToUse":1,"winningItem":""}, {"password":"R9G4Q0","timesToUse":1,"winningItem":""},"password":"CG9RGT","timesToUse":1,"winningItem":""},

What do I need to do to make my JSON file preserve the line breaks?

Thank you!


Solution

  • There is option JSON_PRETTY_PRINT available in json_encode function, if you are using same for encoding json. Try following:

    $json_string = json_encode($data, JSON_PRETTY_PRINT);
    

    Read more about json_encode