在不更改PHP格式的情况下读取和写入JSON文件


Read and write JSON file without changing formatting in PHP

让我们有一个包含JSON的file.json,例如

{
  "first-key": "foo",
  "second-key": "bar"
}

现在,如果我使用PHP内置函数对JSON进行编码和解码,它会更改格式。有没有一种方法可以在不重新格式化JSON的情况下做到这一点?

我需要添加一个密钥,并且文件在Git中提交。因此,我想避免更改那些没有真正更改的行。

JSON_PRETTY_PRINT标志非常接近,无需手动编辑JSON编码的字符串。看起来它应该适用于您的示例。

<?php
$json = '{
  "first-key": "foo",
  "second-key": "bar"
}';
$arr = json_decode($json, true);
$arr['second-key'] = 'baz';
print_r(json_encode($arr, JSON_PRETTY_PRINT));

=

{
    "first-key": "foo",
    "second-key": "baz"
}
<?php
$json = '{
  "first-key": "foo",
  "second-key": "bar"
}';
$arr = json_decode($json, true);
echo "<pre>";
print_r($arr);
echo "</pre>";
$arr_new = array("newKey"=>$arr);
$json_new = json_encode($arr_new);
echo $json_new;
?>