php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #74859 json_decode unexpected behaviour
Submitted: 2017-07-05 18:24 UTC Modified: 2017-07-06 15:27 UTC
From: emimarz at gmail dot com Assigned:
Status: Duplicate Package: JSON related
PHP Version: Irrelevant OS: linux
Private report: No CVE-ID: None
View Add Comment Developer Edit
Anyone can comment on a bug. Have a simpler test case? Does it work for you on a different platform? Let us know!
Just going to say 'Me too!'? Don't clutter the database with that please !
Your email address:
MUST BE VALID
Solve the problem:
23 + 7 = ?
Subscribe to this entry?

 
 [2017-07-05 18:24 UTC] emimarz at gmail dot com
Description:
------------
this unexpected behaviour happen on php 5.* and 7.1 with json_decode



Test script:
---------------
<?php
 
$son = '{
"1":{ "id":"1", "name":"jack" },
"2":{ "id":"2", "name":"john" }
}';

$json = (array) json_decode($son);
//var_dump($json);
var_dump($json['1']); // incorrect result
var_dump($json[1]); // incorrect result
$json = json_decode($son,true);
var_dump($json['1']); // correct result


Patches

Add a Patch

Pull Requests

Add a Pull Request

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2017-07-05 18:33 UTC] peehaa@php.net
-Status: Open +Status: Feedback
 [2017-07-05 18:33 UTC] peehaa@php.net
What unexpected behavior?

Please explain what is expected and why and what the actual result is.
 [2017-07-06 14:57 UTC] emimarz at gmail dot com
-Status: Feedback +Status: Open
 [2017-07-06 14:57 UTC] emimarz at gmail dot com
this two return NULL
var_dump($json['1']); // incorrect result
var_dump($json[1]); // incorrect result

I trying to access an element existent but return NULL
the expected return is something that is not NULL because that element exists
 [2017-07-06 15:27 UTC] requinix@php.net
-Status: Open +Status: Duplicate
 [2017-07-06 15:27 UTC] requinix@php.net
Then this is a(nother) duplicate of a bug that has been fixed with 7.2.
https://3v4l.org/CS6BJ

In PHP 5.x/7.0/7.1, don't cast objects with numeric property names to arrays. Really, avoid creating those sorts of objects in the first place if you can.
For JSON decode straight to an array if you want an array, or in the general case use get_object_vars,
  https://3v4l.org/QcicS
or if you like to hurt yourself then you can use advanced syntax on the object.
  https://3v4l.org/ZARaP
 
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Fri Apr 19 22:01:28 2024 UTC