I can convert my data from JSON to objects using the Perl JSON module (http://search.cpan.org/dist/JSON/), but I am having difficulty accessing the data in perl objects. The data appears to be in an array of hashes, but I cannot use any object accessor functions to get at the data. Here's a sample of the data:
{
"items" : [
{ "name" : "Theodor Nelson",
"id": "_333301"
},
{ "name": "Morton Heilig",
"id": "_13204"
}
]
}
Here's a snippet of my code. Note $inventors_obj holds the data.
$inventors_obj = jsonToObj($inventors_json[0]);
#I want to iterate through my list of inventors
@inventors_array = $inventors_obj->{"items"};
But $inventors_obj->{"items} appears to be returning a single object, rather than an array. How can iterate through it, change things, and print it back to JSON?
#print name doesn't work, because the entire object is #stored at $inv
+entors_array[0].
print $inventors_array[0]->{"name"}
#So this doesn't work:
print $inventors_array[1]->{"name"}
#I am not sure if this is possible to even alter data #generically wit
+h objects, even though I thought they were
#really just arrays of hashes:
$inventors_array[1]->{"name"} = "New Name";
#But I can do with an array of hashes...
$inventors_array[1]{"name"} = "New Name";
However, if I convert the object to an array of hashes (how do I do this, "unblessing"?), can I get it back out in JSON? Is there a way I can manipulate it while keeping it as an object?
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.