Reputation: 143
I using codeigniter. I want to retrive data from database and convert it into JSON object not JSON array.I'm using following code
public function json()
{
$content = $this->db->get('todolist'); //todolist table name
$data = $content->result_array();
echo json_encode($data);
}
Above code is converting database into JSON array. Output
[{"todo_id":"1","todo_content":"Homework","date":"2016-05-05","iscomplete":null,"imagelink":"Lighthouse.jpg"},{"todo_id":"2","todo_content":"exam","date":"2015-04-21","iscomplete":null,"imagelink":"Desert.jpg"},{"todo_id":"3","todo_content":"Lab report","date":"2014-08-29","iscomplete":null,"imagelink":"FB_IMG_14700753538617403.jpg"}]
What will be best way to convert it into JSON object
Upvotes: 3
Views: 1378
Reputation: 26288
Sangam try to understand the concept, check the following line:
$data = $content->result_array(); // $data is an array
echo json_encode($data); // here you are converting it into an json object
Your $data
array contains more than one index in it that's why the json object is having multiple {}
inside []
;
Upvotes: 4
Reputation: 2905
You can use JSON_FORCE_OBJECT see the example below.
echo json_encode($data, JSON_FORCE_OBJECT);
Upvotes: 1
Reputation: 1427
You want to json_encode($data, JSON_FORCE_OBJECT)
.
The JSON_FORCE_OBJECT flag, as the name implies, forces the json output to be an object, even when it otherwise would normally be represented as an array.
Refer: PHP Array to Json Object
Upvotes: 2
Reputation: 627
Assuming you're only getting one row back from your query.
change
echo json_encode($data);
to
echo json_encode($data[0]);
Upvotes: -1