0

I have a .json configuration file. Using PHP, I'm trying to get its contents as an object by json_decode() and validate it. The JSON file contains multi-dimensional data. The problem is with accessing a member in depth dynamically.

For instance, consider the following data:

{
    "somebody": {
        "name": "Ali",
        "age": 13,
        "life": {
            "stat": "good",
            "happy": true
        }
}

How to access the value of the following dynamically?

$happy = $data->somebody->life->happy;

What I mean from a dynamic access is something like this:

$happyIndex = "somebody->life->happy";
$happy = $data->{$happyIndex};

Also, I don't want to use eval().

Thanks.

MAChitgarha
  • 3,728
  • 2
  • 33
  • 40

1 Answers1

0

Assuming you have a JSON data return

 data="{
    "somebody": {
        "name": "Ali",
        "age": 13,
        "life": {
            "stat": "good",
            "happy": true
        }
}"

data = jQuery.parseJSON(data);

then you can navigate to different parts of data by navigating

    var name= data.somebody[0].name;
    var age= data.somebody[0].age;

You will need a $.each function if you have more than one data in "somebody" array.

PHP Version:

$data='{"somebody":{"name": "Ali","age": "13","life": {"stat": "good","happy": "true"} }}';
$data = json_decode($data,TRUE);

$name= $data['somebody']['name']; 
$age= $data['somebody']['age'];
echo("<pre>");
echo($name);
echo($age);
echo("</pre>");
//OUTPUT RESULT Ali 13
Aslan Kayardi
  • 423
  • 1
  • 4
  • 12