JSON output question


I’m pretty new to the whole JSON thing, and I know its more javascript but the problem I’m having is on the php side where I’m generating the JSON code.

The code I have at the moment:

$response["cities"] = array();
	while($c = mysql_fetch_array($cities))
		$response["cities"][$c["cityid"]] = array("id" => (int)$c["cityid"], "name" => $c["name"]);

echo json_encode($response);

This works perfectly, but the problem comes when there are no cities (for the selected country.)

If there is a city the output looks as follows:

{"cities": {"44": {"id": 44, "name": "London"} } }

but if there isn’t a city it looks like this:

{"cities": [] }

where as for use on the javascript side I need it to look like this:

{"cities": {} }

How can I get it to do this?


You’re welcome.

Off Topic:

Hows about not trying to move traffic through to that other site, especially when the same answer had already been posted with more detail? If you’re a spammer, so be it (mods?); if you’re a regular member here, trying to participate then please participate. (:

Off Topic:

The quote styling within off-topic blocks should really be changed to suit.

Thanks all very much, have used the JSON_FORCE_OBJECT option and seems to be working perfectly.

Here is the thread to solve your question


If you’re using PHP 5.3.0 (or above) then you can force it to be an object with the JSON_FORCE_OBJECT option.

echo json_encode($response, JSON_FORCE_OBJECT);

If that’s not an option, then provide an empty object:

if (empty($response['cities'])) {
    $response['cities'] = new stdClass;
echo json_encode($response);

Details of the available options, and more, can be found on the json_encode manual page.

Why do you need it to look like that? It wouldn’t make a huge difference, at least nothing you can’t catch using typeof