user667430
user667430

Reputation: 1547

CakePHP json output

I am trying to output the content i get from my Controller in my view as json, but i think i is outputting weird.

On the web i search json and it comes up with output looking like this:

{"menu": {
  "id": "file",
  "value": "File",
  "popup": {
    "menuitem": [
      {"value": "New", "onclick": "CreateNewDoc()"},
      {"value": "Open", "onclick": "OpenDoc()"},
      {"value": "Close", "onclick": "CloseDoc()"}
    ]
  }
}}

However mine is just not formatted and looks like this.

[{"Customer":{"id":"1","first_name":"Ian","last_name":"Smith","address_1":"10 High Streets","address_2":"","town_city":"Plymouth","county":"Devon","postcode":"PL1 2JD"}},{"Customer":{"id":"2","first_name":"David","last_name":"Smith","address_1":"52 Low Avenue","address_2":"","town_city":"Exeter","county":"Devon","postcode":"EX2 1KO"}}]

How can i output it so it looks like the first one?

EDIT

Controller

$user = $this->Customer->find( 'all' );
$this->set( 'users', $user );

View

<?php echo json_encode($user); ?>

Upvotes: 0

Views: 10218

Answers (2)

Karisters
Karisters

Reputation: 186

There is no sense to beautify your json on output step. If it matters, you may use external tools to make a pretty look of json.

Also, consider using (JSON View) in Cake. In short, you set a special view variable with content you want to jsonify:

  1. for local effect, write in your action Router::parseExtensions()
  2. specify variable which contains your data to be output $this->set('_serialize', array('response')); (in json, there will be a root object called "response" with content of $response variable).

With such approach, you won't need to create view files - json will be output automatically if request has "Accept: application/json" header.

Upvotes: 3

Kishor Kundan
Kishor Kundan

Reputation: 3165

Only difference in those json responses are that the first one is JSON object with sub objects and second one is an array of JSON objects with their sub objects.

The code below retrieves all records for customers. And when you encode it into json object, it is encoded as array of Cutomers

$this->Customer->find( 'all' ); 

You can achieve response like the first one by

$this->Customer->find( 'first' );

The above code will only yield one Customer object.

Upvotes: 0

Related Questions