首页 > 解决方案 > 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 文件中正确附加数据?

标签: phpjqueryjson

解决方案


我认为您的输出没有问题。您正在添加一个不必要的数组层,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);


推荐阅读