473,662 Members | 2,536 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

JSON member access issue

I am using PHP with the JSON extension function json_decode.

I have a JSON with a member named "1" (ie) { "1":"someda ta" }

Trying to access this via the -operator doesn't work, nor does
["1"].

Putting the JSON into a foreach loop DOES access the member:

foreach($json as $key=>$value) {
echo("$key<br />");
}
//outputs '1'

Is this an error on my part, an oversight in the PHP JSON
implementation, or something else? Why can foreach grab the members,
but I can't access them?

Thanks for your time!

Tyler
Jun 2 '08 #1
7 3042
On Tue, 22 Apr 2008 20:32:28 +0200, Logos <ty*********@gm ail.comwrote:
I am using PHP with the JSON extension function json_decode.

I have a JSON with a member named "1" (ie) { "1":"someda ta" }

Trying to access this via the -operator doesn't work, nor does
["1"].

Putting the JSON into a foreach loop DOES access the member:

foreach($json as $key=>$value) {
echo("$key<br />");
}
//outputs '1'

Is this an error on my part, an oversight in the PHP JSON
implementation, or something else? Why can foreach grab the members,
but I can't access them?

The problem is that while json_decode is able to extract it:
object(stdClass )#1 (1) {
["1"]=>
string(8) "somedata"
}

"1" is not a valid property name to use directly.

Workarounds:
Option 1, suitable for single known variable:
<?php
$var = json_decode('{ "1":"someda ta" }');
$name = '1';
echo $var->$name;
?>

Option 2, suited for more generic processing:
<?php
function json_object_to_ named_array($va r){
if(!is_object($ var)){
trigger_error(' No object given');
return;
}
$return = get_object_vars ($var);
foreach($return as &$value){
if(is_object($v alue)) $value = json_object_to_ named_array($va lue);
}
return $return;
}
$test = array('foo' ='bar','foz' =array('fox' ='bax'));
$json = json_encode($te st);
var_dump($json) ;
$var = json_decode($js on);
var_dump($var);
$var = json_object_to_ named_array($va r);
var_dump($var);
?>
Output:
string(33) "{"foo":"bar"," foz":{"fox":"ba x"}}"
object(stdClass )#1 (2) {
["foo"]=>
string(3) "bar"
["foz"]=>
object(stdClass )#2 (1) {
["fox"]=>
string(3) "bax"
}
}
array(2) {
["foo"]=>
string(3) "bar"
["foz"]=>
array(1) {
["fox"]=>
string(3) "bax"
}
}
--
Rik Wasmus
Jun 2 '08 #2
On Apr 22, 3:14 pm, "Rik Wasmus" <luiheidsgoe... @hotmail.comwro te:
On Tue, 22 Apr 2008 20:32:28 +0200, Logos <tyler.st...@gm ail.comwrote:
I am using PHP with the JSON extension function json_decode.
I have a JSON with a member named "1" (ie) { "1":"someda ta" }
Trying to access this via the -operator doesn't work, nor does
["1"].
Putting the JSON into a foreach loop DOES access the member:
foreach($json as $key=>$value) {
echo("$key<br />");
}
//outputs '1'
Is this an error on my part, an oversight in the PHP JSON
implementation, or something else? Why can foreach grab the members,
but I can't access them?

The problem is that while json_decode is able to extract it:
object(stdClass )#1 (1) {
["1"]=>
string(8) "somedata"

}

"1" is not a valid property name to use directly.

Workarounds:
Option 1, suitable for single known variable:
<?php
$var = json_decode('{ "1":"someda ta" }');
$name = '1';
echo $var->$name;
?>

Option 2, suited for more generic processing:
<?php
function json_object_to_ named_array($va r){
if(!is_object($ var)){
trigger_error(' No object given');
return;
}
$return = get_object_vars ($var);
foreach($return as &$value){
if(is_object($v alue)) $value = json_object_to_ named_array($va lue);
}
return $return;}

$test = array('foo' ='bar','foz' =array('fox' ='bax'));
$json = json_encode($te st);
var_dump($json) ;
$var = json_decode($js on);
var_dump($var);
$var = json_object_to_ named_array($va r);
var_dump($var);
?>
Output:
string(33) "{"foo":"bar"," foz":{"fox":"ba x"}}"
object(stdClass )#1 (2) {
["foo"]=>
string(3) "bar"
["foz"]=>
object(stdClass )#2 (1) {
["fox"]=>
string(3) "bax"
}}

array(2) {
["foo"]=>
string(3) "bar"
["foz"]=>
array(1) {
["fox"]=>
string(3) "bax"
}}

--
Rik Wasmus
Ah, I thought it might be something like that then. The JSON notation
is perfectly fine, but PHP's grammar won't let me directly access the
incompatible JSON format. I shall just have to live with it then.

Thanks!

Tyler
Jun 2 '08 #3
Logos wrote:
Ah, I thought it might be something like that then. The JSON notation
is perfectly fine, but PHP's grammar won't let me directly access the
incompatible JSON format. I shall just have to live with it then.
:)

Try echo $var->{1};
Jun 2 '08 #4
On Apr 23, 6:18 pm, Alexey Kulentsov <a...@inbox.ruw rote:
Logos wrote:
Ah, I thought it might be something like that then. The JSON notation
is perfectly fine, but PHP's grammar won't let me directly access the
incompatible JSON format. I shall just have to live with it then.

:)

Try echo $var->{1};
YOU, sirrah, are my HERO! Thank you much much much!!!

:D

Tyler
Jun 2 '08 #5
Logos wrote:
I am using PHP with the JSON extension function json_decode.

I have a JSON with a member named "1" (ie) { "1":"someda ta" }

Trying to access this via the -operator doesn't work, nor does
["1"].
Looks like you're already on your way, but just FYI, the json_decode
function takes an optional second argument that will, if true, cause
objects to be returned as associative arrays instead. Then, the usual
array notation (["1"]) should work.

Dave
Jun 2 '08 #6
On Wed, 30 Apr 2008 03:39:16 +0200, Dave Benjamin
<ra***@lackingt alent.comwrote:
Logos wrote:
>I am using PHP with the JSON extension function json_decode.
I have a JSON with a member named "1" (ie) { "1":"someda ta" }
Trying to access this via the -operator doesn't work, nor does
["1"].

Looks like you're already on your way, but just FYI, the json_decode
function takes an optional second argument that will, if true, cause
objects to be returned as associative arrays instead. Then, the usual
array notation (["1"]) should work.
D'OH! Going through all that trouble writing a recursive function...
--
Rik Wasmus
Jun 2 '08 #7
On Apr 29, 6:39 pm, Dave Benjamin <ra...@lackingt alent.comwrote:
Logos wrote:
I am using PHP with the JSON extension function json_decode.
I have a JSON with a member named "1" (ie) { "1":"someda ta" }
Trying to access this via the -operator doesn't work, nor does
["1"].

Looks like you're already on your way, but just FYI, the json_decode
function takes an optional second argument that will, if true, cause
objects to be returned as associative arrays instead. Then, the usual
array notation (["1"]) should work.

Dave
Keen - I may try that too. Good to know for future reference, in any
event!

Tyler
Jun 2 '08 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

16
2687
by: G Matthew J | last post by:
http://htmatters.net/htm/1/2005/07/evaling-JSON.cfm This is more or less in response to Mr Crockford's admonition a few months ago, "fork if you must". Ironically, although in that usenet post he calls what I am suggesting "brittle", his own Javascript JSON parser is not valid JSON, but rather conforms to my proposed variation on JSON!! With an identifier prepended to the front of the JSON block, and function literals as values: see...
20
6846
by: Luke Matuszewski | last post by:
Welcome As suggested i looked into JSON project and was amazed but... What about cyclical data structures - anybody was faced it in some project ? Is there any satisactional recomendation... PS i am ready to use JSON as data/object interchange when using AJAX and my J2EE project - because it is easier to traverse the JavaScript object than its XML representation (so of course may argue).
8
10405
by: Douglas Crockford | last post by:
There is a new version of JSON.parse in JavaScript. It is vastly faster and smaller than the previous version. It uses a single call to eval to do the conversion, guarded by a single regexp test to assure that it is safe. JSON.parse = function (text) { return (/^(\s|]|"(\\|)*"|-?\d+(\.\d*)?(?\d+)?|true|false|null)+$/.test(text)) && eval('(' + text + ')'); };
3
18131
by: asleepatdesk | last post by:
Hi, I need some help here. When I try to eval() my AJAX returned JSON string, I continually get a javascript error "Expected )". Here's my JSON string: {"recs": }; My js function simply tries to eval() it: var jsonStr = eval('(' + str + ')');
23
3195
by: dhtmlkitchen | last post by:
JSON We all know what it is. In ECMAScript 4, there's a JSON proposal: Object.prototype.toJSONString String.prototype.parseJSON The current proposal, String.prototype.parseJSON, returns an object.
15
7719
RMWChaos
by: RMWChaos | last post by:
As usual, an overly-long, overly-explanatory post. Better too much info than too little, right? A couple weeks ago, I asked for some assistance iterating through a JSON property list so that my code would either select the next value in the member list or the single value. The original post can be found here. This is the code gits helped me write: for (var i = 0; i < attribList.id.length; i++) { var attrib = {};
3
2354
by: belred | last post by:
i tried a couple python json libraries. i used simplejson on the server and was using cjson on the client, but i ran into this issue. i'm now using simplejson on both sides, but i'm still interested in this issue. did i do something wrong? is there a bug in one of the libraries? or something i don't understand about the json spec? i problem is the line where i call cjson.decode() below: '"http:\\/\\/server.com"'
15
2235
RMWChaos
by: RMWChaos | last post by:
In my ongoing effort to produce shorter, more efficient code, I have created a "chicken and egg" / "catch-22" problem. I can think of several ways to fix this, none of them elegant. I want my code to declare var stop if it was not passed to the function. The problem is that stop would be equal to a value dependent on var index that has not been declared yet, but index cannot be created until stop is declared. So you see my chicken and egg...
0
5370
by: crocodilu2008 | last post by:
JSON vs. XML JSON and XML are basically used for the same purpose—to represent and interchange data. I'll try to show you why you might want to use JSON rather than XML in an AJAX context by showing you an example of how an data class (actually, a list of PHP documentation pages) might be represented, first in XML. and then in JSON. This side-by-side comparison should let you begin to understand how to represent data in JSON. The XML version:...
0
8344
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8857
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
8546
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8633
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7367
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5654
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
1
2762
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
1993
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1752
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.