I've a json structure :

{
    "Photos":{
        "Photo":[
            {
                "ID" : 111,
                 "type" : "JPEG",
                "URL": "blabla"  
            },
            {
                "ID": 222,
                "type": "JPG",
                "URL": "blaaaaaaaaa"
            }
        ]
    }
}

Using php-jsonpath only (By stefan Goessner : http://goessner.net/articles/JsonPath), I want to insert a new data (array) into photo identified by 222 such that final output becomes :

{
    "Photos":{
        "Photo":[
            {
                "ID" : 111,
                 "type" : "JPEG",
                "URL": "blabla"  
            },
            {
                "ID": 222,
                "type": "JPG",
                "URL": "blaaaaaaaaa",
                "New_data" : {"CROP": "5x7", "Pixel": "none"}
            }
        ]
    }
}

in actual sense, i want a future possibility of inserting more sub-data as children or grand children of "New_data" as the case may be.

currently i have:

require_once('json.php');           //the parser file lib 
require_once('jsonpath.php');       //the jsonpath evaluator

$parser = new Services_JSON(SERVICE_JSON_LOOSE_TYPE);
$jsonobj = $parser->decode(file_get_contents("filename.json", true));
$result = jsonPath($jsonobj , "$.[1]");

if($result != false){              //this worked flawlessly
     foreach ($result as $path) {

            $keys = explode(';', $path); 

            foreach ($keys as $key) {
                if($key=='$') {
                    continue;
                } else if (is_array($jsonobj)) {
                   $jsonobj[$key][] = array("New_data" => array("CROP" => 5x7, "Pixel" => "none"));  
                } else { 
                    $jsonobj->{$key}[] = array("New_data" => array("CROP" => 5x7, "Pixel" => "none")); 
                }
            }  
      }
 }

file_put_contents("filename.json", $parser->encode($jsonobj));   // write back corrected version

to this extent am confused as the result is unexpectedly positioned elsewhere in filename.json. where am i doing it wrongly, or how else can i do it rightly ? thanks !

From that page you posted:

$.store.book[*].author
the authors of all books in the store

Wouldn't this

$result = jsonPath($jsonobj , "$.[1]");

be more easier if you wrote it as

$result = jsonPath($jsonobj , "$.photos.photo[*]");

You'd have just the photos in an array then, no?

Out of curiosity, what does this do
$keys = explode(';', $path);
There are no ;'s anywhere, does jsonPath add those?

Looks interesting anyway.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.