【问题标题】:json_encode is adding extra square brackets - PHPjson_encode 正在添加额外的方括号 - PHP
【发布时间】: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 中?

标签: php jquery json


【解决方案1】:

我认为您的输出没有问题。您正在通过json_encode(array($data)) 添加一个不必要的数组层,但是当您尝试访问这些值时,您只需要将其考虑到您的 JS 中。您可以像在这个 sn-p 中一样将其作为二维对象数组访问:

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);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-08-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-23
    • 2016-10-16
    • 2020-10-11
    相关资源
    最近更新 更多