#45563 [Bgs]: json_decode fails on json representing javascript objects

From: Date: Tue, 22 Jul 2008 14:04:35 +0000
Subject: #45563 [Bgs]: json_decode fails on json representing javascript objects
References: 1  Groups: php.bugs 
Request: Send a blank email to php-bugs+get-127121@lists.php.net to get a copy of this message
ID: 45563 Updated by: jani@php.net Reported By: coyote4til7 at gmail dot com Status: Bogus Bug Type: JSON related Operating System: Linux PHP Version: 5.2.6 New Comment: Note: This is about JSON, it's not about Javascript. Previous Comments: ------------------------------------------------------------------------ [2008-07-22 14:03:46] jani@php.net Actually you're wrong. From the RFC 4627: object = begin-object [ member *( value-separator member ) ] end-object member = string name-separator value string = quotation-mark *char quotation-mark ------------------------------------------------------------------------ [2008-07-19 13:00:23] coyote4til7 at gmail dot com Description: ------------ When you encode a proper javascript object as json and then use the json_decode function, it fails. The keys in Javascript objects are _not_ supposed to be quoted. If you're going to store a json-encoded object (say in a database) and then reuse it later in javascript, quoting the keys so that php's json_decode function works means that you're counting on the browser's javascript to support something that is not supported by the javascript specification. Reproduce code: --------------- // In javascript, we have an object: // var obj = { parent_id:-1,label:"label" }; // // In javascript, the keys for objects are _not_ quoted by // single or double quotes. So, if we're going to properly encode // this to later reuse it in javascript, we get this sent to php: $json = '[{parent_id:-1,label:"label"}]'; // Let's try to convert it: var_dump(json_decode($json, true)); Expected result: ---------------- { ["parent_id"]=> int(-1) ["label"]=> string(5) "label" } Actual result: -------------- NULL ------------------------------------------------------------------------ -- Edit this bug report at http://bugs.php.net/?id=45563&edit=1

« previous php.bugs (#127121) next »