mcryan
mcryan

Reputation: 1576

PHP access nested object properties from a string literal

I'm trying to come up with a simple approach for extracting data from a multitude of json data sources where the reference is stored in a string literal. This is easy to do when the object structure is known but is there any way to get php to interpret the string literal as it would directly in code?

$data = json_decode('
    {
      "foo": 1,
      "object": {
        "foo": 1.1,
        "bar": 1.2
      },
      "array": [
        "foo",
        "bar"
      ]
    }
');

// Explicitly coded reference all work, of course
var_dump($data->foo); // int(1)
var_dump($data->object->foo); // float(1.1)
var_dump($data->array[0]); // string(3) "foo"

And I know that I can access an object's property from a string literal like this:

$string = 'foo';
var_dump($data->$string); // int(1)
var_dump($data->object->$string); // float(1.1)

Is there any way to go about achieving this for the second and third references, without having to break up the string and loop through the object recursively until each element is found?

$string = 'object->foo';
var_dump($data->$string);

$string = 'array[0]';
var_dump($data->$string);

If there is nothing native to PHP for handling this, is there a library or anything that I could use to make this process easier?

Edit: To provide some extra clarity, this is an application where a JSON feed can be configured through the UI and an administrator can extract values from the JSON feed. This works fine for simpler JSON structures but breaks down when they're trying to pull a value such as $foo->bar->baz[0]->qux->corge. I'm trying to find an easier way to get values such as this when the structure changes and I can't account for every possibility within the code.

Upvotes: 0

Views: 325

Answers (1)

Daniel Klischies
Daniel Klischies

Reputation: 1135

Since you are using JSON, i‘d use JSON Pointers. Here is their official spec

What they do is providing a query language for json objects (similar to XPath for XML). Accessing your foo within object would result in a query like /object/foo.

Now you‘d have your users specify the json pointer queries, and use a json pointer library to perform the actual queries. This has the advantage that if you ever decide to ditch PHP for say Java, you’d only need to use a JSON Pointer implementation for Java and your users won‘t be impacted by the change.

Upvotes: 1

Related Questions