1

I need some help about this problem. I need to add object that encompasses the hash of my json file.

I use services module in drupal 6 for generate xml and json file from my nodes. So, when i view my nodes in json i have this:

[
{
"nid": "7",
"vid": "7",
"type": "page",
"language": "",
"title": "Bievenido", ..... } ]

But i need that this json file look like this:

[
{
"<whatever>": {
    "nid": "7",
    "vid": "7",
    "type": "page",
    "language": "",
    "title": "Bievenido", .....  } ]

How to change this json file generated by services module?

1 Answer 1

2

The JSON is generated by the RESTServerViewBuiltIn class in the services/servers/rest_server/includes/rest_server.views.inc file, specifically the render_json member function.

Services does provide a way to override this.

Firstly in a custom module implement hook_rest_server_response_formatters_alter and change the View class that's used to render the output to a custom one:

function MYMODULE_rest_server_response_formatters_alter(&$formatters) {
  $formatters['json']['view'] = 'RESTServerViewMYMODULE';
}

Then add your custom View class (I'd keep this in the module file to avoid having to load includes):

class RESTServerViewMYMODULE extends RESTServerView {
  public function render() {
    $new_data = new stdClass;
    $new_data->some_key = $this->model;

    $json = str_replace('\\/', '/', json_encode($new_data));

    return $json;
  }
}

Hope that helps

2
  • I don't understand the part of $json = str_replace('\\/', '/', json_encode($data)); . In this part the own method convert to json file. How to override this conversion?... Do you have an example of this?
    – Dvex
    Commented Jan 25, 2012 at 20:43
  • @Dvex: I've updated the answer to show you exactly how to wrap the existing data in a new object and serialise it JSON.
    – Clive
    Commented Jan 26, 2012 at 17:38

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.