duanqin4238 2018-06-14 11:56
浏览 124
已采纳

跨多行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!

  • 写回答

1条回答 默认 最新

  • doujiayuan8415 2018-06-14 12:00
    关注

    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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用
  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?