1.2.1353. Use json_decode() Options

json_decode() returns objects by default, unless the second argument is set to TRUE or JSON_OBJECT_AS_ARRAY. Then, it returns arrays.

Avoid casting the returned value from json_decode(), and use the second argument to directly set the correct type. Note that all objects will be turned into arrays, recursively. If you’re expecting an array of objects, don’t use the JSON_OBJECT_AS_ARRAY constant, and change your JSON code.

Note that JSON_OBJECT_AS_ARRAY is the only constant : there is no defined constant to explicitly ask for an object as returned value.

<?php

$json = '{"a":"b"}';

// Good syntax
$array = json_decode($json, JSON_OBJECT_AS_ARRAY);

// GoToo much work
$array = (array) json_decode($json);

?>

See also json_decode.

1.2.1353.1. Suggestions

  • Use the correct second argument of json_decode() : JSON_OBJECT_AS_ARRAY

1.2.1353.2. Specs

Short name

Structures/JsonWithOption

Rulesets

All, Suggestions

Exakat since

1.4.3

PHP Version

All

Severity

Major

Time To Fix

Quick (30 mins)

Precision

Very high

Features

json

Available in

Entreprise Edition, Exakat Cloud