1

In PHP figured out how to use {name-with-reserved-chars} notation to access object data after JSON decode but I also have index values as well in the path (like [0]). My attempts to add the index value has returned nothing despite all my attempts to vary the pattern. Here is an example based on a big JSON object:

["ops:world-patent-data"]["exchange-documents"]["exchange-document"]
[0]["bibliographic-data"]["publication-reference"]["document-id"][0].date.$

my attempt gets nothing:

print $result->{'ops:world-patent-data'}->{'exchange-documents'}->{'exchange-document'}->
      {0}->{'bibliographic-data'}->{'publication-reference'}->{'document-id'}->{0}->date;

wondering how to place the 0 and 1 indexes in the path ...

Jared Farrish
  • 48,585
  • 17
  • 95
  • 104
  • You probably want `[0]`, note the square braces instead of curly `{0}`. – Jared Farrish Feb 03 '13 at 22:06
  • 2
    Or even simpler, use `json_decode($in, TRUE)` to get a plain array without mixed objects and lists. – mario Feb 03 '13 at 22:08
  • @mario - Only simpler if you point out the square bracket notation needed for all keys and numeric indexes (unless I'm wrong...?). (And I think *easier* is in the eye of the beholder. Why is it easier?) – Jared Farrish Feb 03 '13 at 22:10
  • @JaredFarrish True. To me it's simpler to traverse anyway if it's a coherent hash. The `{'..'}` complex string syntax is sometimes prettier, but often feels like a workaround. -- To OP: You might wish to paste your JSON into http://array.include-once.org/ to see how to access nodes either way. – mario Feb 03 '13 at 23:13
  • @mario - I agree in general, just wanted to make sure the OP understood what was being proposed as well what was actually wrong with what was given. – Jared Farrish Feb 04 '13 at 13:36

1 Answers1

3

When deserializing an actual JSON list (i.e, not an object but an actual array with numerical indices; something like [1,2,3,...] or also [{...},{...},...]), PHP's parse_json function builds a corresponding PHP array with numerical indices (while on the other hands, it maps JSON objects to instances of the stdClass class -- unless you use the $assoc parameter of the parse_json function).

So, because you are accessing arrays instead of objects, your code would probably have to look like this:

print $result->{'ops:world-patent-data'}->{'exchange-documents'}->
    {'exchange-document'}[0]->{'bibliographic-data'}->{'publication-reference'}->
    {'document-id'}[0]->date;

It would probably easier to use the $assoc parameter, forcing json_decode to map the entire JSON object with associative arrays, allowing you to use the square bracket notation for object access also.

helmbert
  • 35,797
  • 13
  • 82
  • 95