PHP's Object Notation: Accessing Fields/Members With Hyphens in Their Name

| No TrackBacks
Here's another quick tip; I fought through this issue today at work.  In PHP, you might have a need to parse some JSON that contains a field/member name with one or more hyphens.  Here's an example:

{
"field-one" : 1,
"field-two" : 2,
"field-three" : [ 1, 2, 3 ]
}

Most JSON libraries should convert this JSON string into a native object with ease.  However, in PHP when you try to access $obj->field-one directly, PHP will complain given the hyphen in the member name.  The solution to this simple problem, is to wrap the name in curly braces, like so:

$obj->{'field-one'}

Here's a more complete example using Services_JSON in PHP:

<?php

require_once("JSON.php");
$json = new Services_JSON();

$string = "{\"field-one\":1,\"field-two\":2," .
"\"field-three\":[1,2,3]}";

$obj = $json->decode( $string );

// Will FAIL
//echo $obj->field-one;

// WORKS
echo $obj->{'field-one'};

?>

For your download convenience, you can find the latest Services_JSON library here (as of 4/22/09).  The official PEAR CVS repository for Services_JSON can be found here.  Enjoy.

Did You Find this Helpful?

Did you find this post helpful, or at least, interesting?

  

Send Mark a Direct Message

If you'd like to send me a direct message, please do so below. However, I do not publicly post comments or messages submitted directly to me. So, if you're going to try to SPAM me, or my blog, you're pretty much wasting your time.

400 characters remaining

Error

About Mark

A Silicon Valley native, Mark Kolich is a full-time Software Engineer, a casual entrepreneur, and a consultant for hire. A web technologies expert, his current focus is on building powerful and robust cloud-driven web-applications using Java, PHP, Perl, AJAX, DHTML, CSS, and JavaScript. His favorite programming languages are PHP, Java and JavaScript. He uses Linux, enjoys biking to work, loves building great software, and always writes elegant, readable, and maintainable code.

No TrackBacks

No trackbacks attached to this entry.

Twitter (@markkolich)

Translate

About this Entry

This page contains a single entry by Mark Kolich published on April 22, 2009 5:59 PM.

Java to Capitalize the First Letter of Each Word in a Sentence was the previous entry in this blog.

5 Quick and Simple Tips to Better Secure your MySQL Server is the next entry in this blog.

Find recent content on the main index or look in the archives to find all content.