How to get an array instead of object when requesting JSON data using HTTPful
arrays, httpful, json, php, rest
Solution
It may be a little late to answer this, but I did a little research while using Httpful and found the answer. Httpful uses a default set of handlers for each mime type. If one is registered before you send the request, it will use the one you registered. Conveniently, there is an `Httpful\Handlers\JsonHandler` class. The constructor takes an array of arguments. The only one it uses is `$decode_as_array`. Therefore, you can make it return an array like this:
// Create the handler
$json_handler = new Httpful\Handlers\JsonHandler(array('decode_as_array' => true));
// Register it with Httpful
Httpful\Httpful::register('application/json', $json_handler);
// Send the request
$response = Request::get('some-url')->send();
UPDATE
I realized that it sometimes parses the response into a funky array if you don't tell the request to expect JSON. The docs say it's supposed to work automagically, but I was having some issues with it. Therefore, if you get weird output, try explicitly telling the request to expect JSON like so:
$response = Request::get('some/awesome/url')
->expects('application/json')
->send();
Problem
I'm using HTTPful to send some requests in PHP and get data in JSON, but the library is converting the result into objects, where I want the result to be an array. In other words, its doing a `json_decode($data)` rather than `json_decode($data, true)`. There is, somewhere, an option to use the latter, but I can't figure out where. The option was added in v0.2.2: ``` - FEATURE Add support for parsing JSON responses as associative arrays instead of objects ``` But I've been reading documentation and even the source, and I don't see the option anywhere... The only way I can think of is making my own `MimeHandlerAdapter` which does a `json_decode($data, true)` but it seems like a pretty backwards way of doing it if there is an option somewhere...