Skip to content

Commit bb94e9b

Browse files
committed
Issue #22 - can't stringify assoc arrays
Detect if the array in question is considered associative -- keys are not a sequential range of numbers starting from 0. If it is associative, convert it to an object and allow the stringify process to turn it into a HJSON object representation.
1 parent 8b25640 commit bb94e9b

4 files changed

Lines changed: 36 additions & 1 deletion

File tree

src/HJSON/HJSONStringifier.php

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -239,6 +239,17 @@ private function str($value, $hasComment = null, $noIndent = null, $isRootObject
239239
case 'array':
240240
$isArray = is_array($value);
241241

242+
$isAssocArray = function (array $arr) {
243+
if (array() === $arr) {
244+
return false;
245+
}
246+
return array_keys($arr) !== range(0, count($arr) - 1);
247+
};
248+
if ($isArray && $isAssocArray($value)) {
249+
$value = (object) $value;
250+
$isArray = false;
251+
}
252+
242253
$kw = null;
243254
$kwl = null; // whitespace & comments
244255
if ($this->keepWsc) {
@@ -324,7 +335,7 @@ private function str($value, $hasComment = null, $noIndent = null, $isRootObject
324335
}
325336
} else {
326337
foreach ($value as $k => $vvv) {
327-
$v = $this->str($value->$k);
338+
$v = $this->str($vvv);
328339
if ($v !== null) {
329340
$partial[] = $this->quoteName($k) . ($startsWithNL($v) ? ':' : ': ') . $v;
330341
}

tests/assets/pass1_result.hjson

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,14 @@
88
}
99
{}
1010
[]
11+
{
12+
1: foo
13+
3: bar
14+
}
15+
{
16+
foo: foo
17+
bar: bar
18+
}
1119
-42
1220
true
1321
false

tests/assets/pass1_result.json

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,14 @@
77
},
88
{},
99
[],
10+
{
11+
"1": "foo",
12+
"3": "bar"
13+
},
14+
{
15+
"foo": "foo",
16+
"bar": "bar"
17+
},
1018
-42,
1119
true,
1220
false,

tests/assets/pass1_test.json

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,14 @@
33
{"object with 1 member":["array with 1 element"]},
44
{},
55
[],
6+
{
7+
"1": "foo",
8+
"3": "bar"
9+
},
10+
{
11+
"foo": "foo",
12+
"bar": "bar"
13+
},
614
-42,
715
true,
816
false,

0 commit comments

Comments
 (0)