Drupal - How do I consume JSON data via a hook_menu callback?

Well, it turns out I was getting the data, but I forgot to decode it...

In my hook_menu callback:

$received = file_get_contents("drupal://input"); // Use inputstream module.
$received = json_decode($received, TRUE);

Then I can play around as much as I'd like with the $received value.

Additionally, the inputstream module is invaluable in letting me get to the input stream more than once (if you try using php://input more than once, the second time, and those following, will return NULL).

As an additional note, I just noticed today a new module that might be an even simpler way of handling this: Content as JSON


The REST Server that is part of the Services module does this automatically for JSON as well as for other formats: http://drupal.org/project/services

It also supports Inputstream (Inputstream was built to handle both OAuth verification and Services decoding of the same stream).

Tags:

Services