Formatting json response for jQuery upload Plugin

221 views Asked by At

I am using jQuery Upload File plugin and trying to integrate database to it. I need to output the json response correct format like that :

{"files": [
  {
    "id": 1,
    "name": "picture1.jpg"
  },
  {
    "id": 2,
    "name": "picture2.jpg"
  }
]}

What I have at the moment :

[
  {
    "id": 1,
    "name": "picture1.jpg"
  },
    "id": 2,
    "name": "picture2.jpg"
  }
]

My php file looks like that :

$files= array();
$db = new DB;
$query = $db->get_rows("SELECT * FROM `files` ORDER BY `name`");

foreach ($query as $row) {   
  $file = new stdClass();
  $file->id = $row->id;
  $file->name = $row->name;
  array_push($files,$file);
}

header('Content-type: application/json');
echo json_encode($files);
2

There are 2 answers

0
AudioBubble On BEST ANSWER
$files= array();
$db = new DB;
$query = $db->get_rows("SELECT * FROM `files` ORDER BY `name`");

foreach ($query as $row) {   
  $file = new stdClass();
  $file->id = $row->id;
  $file->name = $row->name;
  array_push($files,$file);
}

header('Content-type: application/json');
echo json_encode(array('files' => $files));
2
Ido On
$t = '[{"id": 1,  "name": "picture1.jpg"}, {"id": 2, "name": "picture2.jpg"}]';

$t = json_decode($t, true);
$t = array("files" => $t);

echo json_encode($t);

Output:

{"files":[{"id":1,"name":"picture1.jpg"},{"id":2,"name":"picture2.jpg"}]}

Or with your code simply do:

$files= array();
$db = new DB;
$query = $db->get_rows("SELECT * FROM `files` ORDER BY `name`");

foreach ($query as $row) {   
  $file = new stdClass();
  $file->id = $row->id;
  $file->name = $row->name;
  array_push($files,$file);
}

header('Content-type: application/json');
echo json_encode(array("files" => $files));