3

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

1
  • Do you want the keys of the object to be numerical? Why do you even want to force an object? Commented Dec 19, 2016 at 5:39

4 Answers 4

4

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 [];

Sign up to request clarification or add additional context in comments.

1 Comment

Thumbs up! This is what really happening with you. You need to iterate that object by javascript if you want the values to process.
2

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

Comments

1

You can use JSON_FORCE_OBJECT see the example below.

 echo json_encode($data, JSON_FORCE_OBJECT);

Comments

-1

Assuming you're only getting one row back from your query.

change

echo json_encode($data);

to

echo json_encode($data[0]);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.