如何用PHP向JSON格式文件追加内容并在JavaScript中解析为对象
需求与问题
我现在需要实现两个关联功能:
- 每次创建用户账户时,将用户的账号、密码以JSON格式追加到
UserJSON.txt文件中,目前我写的PHP代码如下:
<?php $myObj->username = $username; $myObj->password = $password; $myJSON = json_encode($myObj); $stringJSON = $myJSON.","; print $stringJSON; $myfile = file_put_contents('UserJSON.txt', $stringJSON.PHP_EOL , FILE_APPEND | LOCK_EX); fclose('UserJSON.txt'); ?>
- 用JavaScript读取这个
UserJSON.txt文件,并将其中的每一条JSON数据转换为JavaScript对象。
举个例子,UserJSON.txt的内容大概是这样的:
{"username":"alice","password":"123456"}, {"username":"bob","password":"abcdef"},
解决方案
首先得提一下:你当前的PHP代码写入的内容存在两个小问题——一是每条JSON后面都加了逗号,最后一条数据的逗号会导致内容不是合法的JSON结构;二是所有数据没有被包裹在数组[]里,这会给JS解析带来额外麻烦。我先给你优化PHP写入逻辑,再处理JS的读取转换。
步骤1:优化PHP写入逻辑
我们可以让文件内容始终保持为标准的JSON数组格式,这样JS读取后能直接解析成对象数组,可靠性更高。修改后的PHP代码如下:
<?php // 先读取现有文件内容 $fileContent = file_get_contents('UserJSON.txt'); // 初始化用户数组 $users = []; // 如果文件有内容,尝试解析为数组 if (!empty($fileContent)) { $users = json_decode($fileContent, true); // 处理解析失败的异常情况 if (json_last_error() !== JSON_ERROR_NONE) { $users = []; } } // 创建新用户对象 $newUser = [ 'username' => $username, 'password' => $password ]; // 将新用户追加到数组 $users[] = $newUser; // 重新编码为格式化的JSON并写入文件 file_put_contents('UserJSON.txt', json_encode($users, JSON_PRETTY_PRINT), LOCK_EX); ?>
优化后UserJSON.txt的内容会是标准的JSON数组,比如:
[ {"username":"alice","password":"123456"}, {"username":"bob","password":"abcdef"} ]
步骤2:用JavaScript读取并转换数据
分两种常见场景处理:
场景1:浏览器端JavaScript(前端)
在浏览器里,我们可以用fetch API读取文件,直接解析成JSON对象数组:
fetch('UserJSON.txt') .then(response => { if (!response.ok) { throw new Error('无法读取用户数据文件'); } return response.json(); }) .then(users => { // users就是转换后的对象数组,每条都是包含username和password的用户对象 console.log('用户列表:', users); // 示例:遍历每个用户 users.forEach(user => { console.log(`用户名:${user.username},密码:${user.password}`); }); }) .catch(error => { console.error('读取失败:', error); });
场景2:Node.js环境(后端)
如果是在Node.js里读取文件,可以用内置的fs模块:
const fs = require('fs').promises; async function readUserList() { try { // 读取文件内容 const fileContent = await fs.readFile('UserJSON.txt', 'utf8'); // 解析为对象数组 const users = JSON.parse(fileContent); console.log('用户列表:', users); // 示例:遍历用户 users.forEach(user => { console.log(`用户名:${user.username},密码:${user.password}`); }); } catch (error) { console.error('读取或解析失败:', error); } } // 执行读取函数 readUserList();
如果暂时不想修改PHP代码,需要兼容原来那种每条加逗号的文本格式,JS可以这样处理:
// 浏览器端兼容示例 fetch('UserJSON.txt') .then(response => response.text()) .then(text => { // 拆分每行内容,过滤空行 const lines = text.split('\n').filter(line => line.trim() !== ''); // 去掉每行末尾的逗号,整理成合法的JSON字符串 const validJsonStrings = lines.map(line => line.trim().replace(/,$/, '')); // 拼成完整的JSON数组 const jsonArrayStr = `[${validJsonStrings.join(',')}]`; // 解析为对象数组 const users = JSON.parse(jsonArrayStr); console.log('用户列表:', users); }) .catch(error => console.error('处理失败:', error));
不过还是更推荐用标准JSON数组的写入方式,解析逻辑更简洁可靠。
内容的提问来源于stack exchange,提问作者SQLUser
相关产品推荐
相关产品推荐

