Skip to content

Sparse Arrays #15

@rodneyrehm

Description

@rodneyrehm
<input name="mix[0]" value="alpha">
<input name="mix[5]" value="bravo">
<!--
  { mix: ["alpha", null, null, null, null, "bravo"] }
  mix[0]=alpha&mix[5]=bravo
-->

This has been pointed out before: This is not only "ugly", it's a trivial DoS waiting to happen.

While this was trying to be developer friendly, a simple "fix" can be found in PHP's json_encode: sequential vs. non-sequential array example. If the keys of a map do not fulfill the following condition, the map is not converted to array, but serialized to object:

var data = {"0": "alpha", "1": "bravo", "2": "charlie"};
// all indexes must be integer
var _notInteger = /[^0-9]/
var _invalidKeys = Object.keys(data).some(_notInteger.test, _notInteger);
var keys = Object.keys(data).map(Number);
var _invalidKeys = keys.some(function(value){ return isNaN(value) });
// lowest index must be 0
var _lowerBound = Math.min.apply(Math, keys) !== 0;
// highest index must be exactly 
var _upperBound = Math.max.apply(Math, keys) !== keys.length - 1;

if (_invalidKeys || _lowerBound || _upperBound) {
  // serialize to Object
} else {
  // serialize to Array
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions