php - json_encode 正在添加额外的方括号 - PHP
问题描述
当我使用 php 将代码写入 json 文件时,json_encode 会添加额外的方括号。创建和编写 JSON 文件的方法。
function appendData($data){
$filename='data.json';
// read the file if present
$handle = @fopen($filename, 'r+');
// create the file if needed
if ($handle === null)
{
// $handle = fopen($filename, 'w+');
$handle = fopen($filename, 'w') or die("Can't create file");
}
if ($handle)
{
// seek to the end
fseek($handle, 0, SEEK_END);
// are we at the end of is the file empty
if (ftell($handle) > 0)
{
// move back a byte
fseek($handle, -1, SEEK_END);
// add the trailing comma
fwrite($handle, ',', 1);
// add the new json string
fwrite($handle, json_encode($data,JSON_UNESCAPED_SLASHES) . ']');
}
else
{
// write the first event inside an array
fwrite($handle, json_encode(array($data),JSON_UNESCAPED_SLASHES));
}
// close the handle on the file
fclose($handle);
}
}
使用数据数组参数调用方法
$file= appendData($data);
数据
$data= array(
'name' => "abc",
'image_url' => "cdf",
);
JSON输出就像
[[{"name":"Apple iPhone 6S\u00a0with FaceTime\u00a0- 32GB, 4G LTE, Gold","image_url":"https://m.media-amazon.com/images/I/51jV7zsrOtL._AC_UL436_.jpg"}]]
问题:在 json 输出中附加了额外的方括号,这似乎很好,因为使用json_encode(array($data))
. 但它不会在前端使用 javascript 或 jquery 进行解析。
问题:如何使用 jquery 解析这个双正方形 JSON 数据或如何使用 php 在 json 文件中正确附加数据?
解决方案
我认为您的输出没有问题。您正在添加一个不必要的数组层,json_encode(array($data))
但是当您尝试访问这些值时,您只需要将其考虑到您的 JS 中。您可以将其作为二维对象数组访问,如以下代码段所示:
let json = '[[{"name":"Apple iPhone 6S\u00a0with FaceTime\u00a0- 32GB, 4G LTE, Gold","image_url":"https://m.media-amazon.com/images/I/51jV7zsrOtL._AC_UL436_.jpg"}]]';
let v = JSON.parse(json);
console.log(v[0][0].name);
console.log(v[0][0].image_url);
推荐阅读
- google-apps-script - 更改样式 Browser.msgBox / 更改样式 Browser.msgBox
- gulp - 转换为有效的 Gulp 4 文件
- mongodb - 为什么我得到“dateFromString 无法识别的参数:'format'”,尽管 db 版本 >3.6 支持聚合
- azure - 如何使用消费计划为 azure 函数设置无限超时
- php - 从 phonegap android 应用程序发送电子邮件
- sql - 获取四个日期列的差异
- node.js - 如何修复“来自 lcovParse 的错误:”“无法解析字符串”?在 circleICI v2.0 上使用带有 mocha 的工作服
- google-cloud-platform - Google Cloud - 检测离线设备
- ios - MapBox:MGLineStyleLayer 绘制在 Annotations 上
- semantic-ui-react - Semantic UI React Dropdown:标题选项?