我有这个示例 JSON 文件:
{
"users":[
{"username":"user123","password":"123321abc"},
{"username":"user124","password":"123321abc"},
{"username":"user125","password":"123321abc"}
]
}
我这样设置它,因为我需要使用 fgets 在 php 中阅读它。喜欢这个:
<?php
$newUser = ["username"=>"user123","password"=>"123321abc"];
$jsonFile = fopen("JSONsample.json","r+");
while(($line = fgets($jsonFile) != false){
$oldUser = json_decode($line,true);
if($oldUser["username"] === newUser["username"]){
if($newUser["password"] === oldUSer["password"]){
doSomething($newUser);
}
}
?>
问题是fgets
读取不是完整 json 对象的行时,它会返回null
.因此,它将前两个用户对象读取为行尾逗号的空值。我可以删除逗号,它会根据需要返回用户。但它作为一个整体不是一个有效的 JSON。我需要"用户"数组用于其他功能。
所以,我的问题是,有什么方法可以安排我的 JSON,使其作为一个整体并在逐行读取时成为一个有效的 JSON 文件?
确保每行都以大括号"{"开头,以大括号"}"结尾。然后,您可以假设它是一个有效的 JSON,然后应用json_decode
function startsWith($haystack, $needle)
{
$length = strlen($needle);
return (substr($haystack, 0, $length) === $needle);
}
function endsWith($haystack, $needle)
{
$length = strlen($needle);
if ($length == 0) {
return true;
}
return (substr($haystack, -$length) === $needle);
}
$newUser = ["username"=>"user123","password"=>"123321abc"];
$jsonFile = fopen("JSONsample.json","r+");
while(($line = fgets($jsonFile) != false){
$line = trim($line);
if(!startswith($line,"{") || !endswith($line,"}")) continue;
$oldUser = json_decode($line,true);
if($oldUser["username"] === newUser["username"] && $newUser["password"] === oldUSer["password"]){
doSomething($newUser);
}
}
$json_file_data = json_decode(file_get_contents('JSONsample.json'), true);
$users_info = $json_file_data.users;
$newUser = $users_info[0];
$oldUser = $users_info[1];
我想你可以很容易地从这里获取数据,让我知道我是否可以帮助ypu。
有作曲家包通过解析文件流来解决内存问题,而不是将其全部读入内存,例如包salsify/json-streaming-parser
:
在包装师: https://packagist.org/packages/salsify/json-streaming-parser
在 GitHub 上: https://github.com/salsify/jsonstreamingparser