【发布时间】:2019-10-04 19:17:19
【问题描述】:
json_encode 在我使用 php 将代码写入 json 文件时添加了额外的方括号。 创建和写入 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格式了。
-
数据为数组格式
-
你能分享那个数组吗?为什么这个
array($data)和这个. ']'? -
console.log(JSON.parse('[[{"name":"Apple iPhone 6S\u00a0with FaceTime\u00a0- 32GB, 4G LTE, Gold","image_url":"https://m.media-amazon.com/images/I/51jV7zsrOtL._AC_UL436_.jpg"}]]'))没有问题,我得到了你所期望的结果。 -
@Nick 但是我们不能这样做
console.log(result.name)或者如何解析和获取数据以从这个 json 中显示在 HTML 中?