Esar-ul-haq Qasmi
Esar-ul-haq Qasmi

Reputation: 1084

json_encode is adding extra square brackets - PHP

json_encode is adding extra square bracket when I write code in to the json file using php. METHOD to create & write JSON file.

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

Method call with data array argument

$file=  appendData($data);

Data

    $data= array(
    'name'    => "abc",
    'image_url' => "cdf", 
);

The JSON Output comes like

[[{"name":"Apple iPhone 6S\u00a0with FaceTime\u00a0- 32GB, 4G LTE, Gold","image_url":"https://m.media-amazon.com/images/I/51jV7zsrOtL._AC_UL436_.jpg"}]]

Problem: There are extra square brackets appending in json output, that seems fine becuase of using json_encode(array($data)) . But it doesn't parse on front end using javascript or jquery.

Question: how to parse this double square JSON data using jquery or how to append data properly in json file using php?

Upvotes: 0

Views: 729

Answers (1)

Nick
Nick

Reputation: 147166

I see no problem with your output. You are adding an unnecessary layer of array by json_encode(array($data)) but you just have to factor that into your JS when you try to access the values. You can access it as a 2-d array of objects as in this snippet:

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

Upvotes: 2

Related Questions