php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #42303 json_encode() creates objects when array has gaps in the index
Submitted: 2007-08-15 06:34 UTC Modified: 2007-08-15 19:46 UTC
From: dev at lenss dot nl Assigned:
Status: Closed Package: JSON related
PHP Version: 5.2CVS-2007-08-14 OS: *
Private report: No CVE-ID: None
 [2007-08-15 06:34 UTC] dev at lenss dot nl
Description:
------------
When encoding an array with sequental keys. Everything works out fine. When encoding an array with gaps between the keys. The json encoder creates an object instead of an array. Wich maybe ideal in some places. But it's inconsistant with the JSON javascript parser at json.org. I selected the PHP 4.4.7 version. But also tested in PHP 5.2.3 with the same result.

In json.c the following code is causing this:

--- ext/json/json.c.orig	2007-08-14 22:38:20.000000000 +0200
+++ ext/json/json.c	2007-08-14 22:36:51.000000000 +0200
@@ -106,10 +106,6 @@
 
             if (i == HASH_KEY_IS_STRING) {
                 return 1;
-            } else {
-                if (index != idx) {
-                    return 1;
-                }
             }
             idx++;
         }

Reproduce code:
---------------
<?php
/**
* Create an array with ordered keys from 0 to 1
*/
$main = array();
$element1 = array();
$element2 = array();
$element1[0] = "foo";
$element2[0] = "bar";
$element2[1] = "test";
$main[0] = $element1;
$main[1] = $element2;

echo "Result in array: " . json_encode($main) . "\n";

/**
* Create an array without ordered keys from 0 to 2
*/
$main2 = array();
$element1 = array();
$element2 = array();
$element1[0] = "foo";
$element2[0] = "bar";
$element2[1] = "test";
$main2[0] = $element1;
$main2[2] = $element2;

echo "Result in object: " . json_encode($main2) . "\n";
?>

Expected result:
----------------
Result in array: [["foo"],["bar","test"]]
Result in object: [["foo"],["bar","test"]]

Actual result:
--------------
Result in array: [["foo"],["bar","test"]]
Result in object: {"0":["foo"],"2":["bar","test"]}

Patches

Add a Patch

Pull Requests

Add a Pull Request

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2007-08-15 08:42 UTC] dev at lenss dot nl
Changed version of report to PHP 5.2.3.
 [2007-08-15 09:39 UTC] dev at lenss dot nl
Tested the snaps on windows and linux. Bug still is active in the snapshots.
 [2007-08-15 18:15 UTC] iliaa@php.net
The problem is that if you save a non-sequential array as an array you 
lose the sequence and encoding process re-enumerates the array values

so array(0 => foo, 2 => bar) becomes array(0 => foo, 1 => bar)
 [2007-08-15 19:46 UTC] dev at lenss dot nl
I know it re-enumerates the array. That's what the javascript JSON encoder does. 

But when i think of it. It's probably better how it is.

Thnx for the support.
 
PHP Copyright © 2001-2019 The PHP Group
All rights reserved.
Last updated: Sat Dec 14 16:01:23 2019 UTC