Sample code for 30+ languages & platforms
PHP Requires Chilkat v11.0.0+

Modify Parts of JSON Document

See more JSON Examples

Demonstrates how to modify parts of a JSON document. This example uses the following JSON document:
{
   "fruit": [
      	{
         "kind": "apple",
	 "count": 24,
	 "fresh": true,
	 "extraInfo": null,
	 "listA": [ "abc", 1, null, false ],
	 "objectB": { "animal" : "monkey" }
      	},
	{
         "kind": "pear",
	 "count": 18,
	 "fresh": false,
	 "extraInfo": null
	 "listA": [ "xyz", 24, null, true ],
	 "objectB": { "animal" : "lemur" }
	}
    ],
    "list" : [ "banana", 12, true, null, "orange", 12.5, { "ticker": "AAPL" }, [ 1, 2, 3, 4, 5 ] ],
    "alien" : true
}

Chilkat PHP Downloads

Chilkat2 PHP
<?php

use Chilkat2\JsonArray;
use Chilkat2\JsonObject;

$json = new JsonObject();

// Load the JSON from a file.
try {
    $json->LoadFile('qa_data/json/modifySample.json');
} catch (\Chilkat2\Exception $e) {
    echo $e->getMessage(), "\n";
    exit;
}

// This example will not check for errors (i.e. null / false / 0 return values)...

// Get the "list" array:

$listA = new JsonArray();

$json->ArrayOf2('list', $listA);

// Modify values in the list.

// Change banana to plantain
$listA->SetStringAt(0, 'plantain');

// Change 12 to 24
$listA->SetIntAt(1, 24);

// Change true to false
$listA->SetBoolAt(2, false);

// Is the 3rd item null?
$bNull = $listA->IsNullAt(3);

// Change "orange" to 32.
$listA->SetIntAt(4, 32);

// Change 12.5 to 31.2
$listA->SetNumberAt(5, '31.2');

// Replace the { "ticker" : "AAPL" } object with { "ticker" : "GOOG" }
// Do this by deleting, then inserting a new object at the same location.
$listA->DeleteAt(6);
$tickerObj = new JsonObject();
$listA->AddObjectAt2(6, $tickerObj);

$tickerObj->AppendString('ticker', 'GOOG');

// Replace "[ 1, 2, 3, 4, 5 ]" with "[ "apple", 22, true, null, 1080.25 ]"
$listA->DeleteAt(7);
$aa = new JsonArray();
$listA->AddArrayAt2(7, $aa);

$aa->AddStringAt(-1, 'apple');
$aa->AddIntAt(-1, 22);
$aa->AddBoolAt(-1, true);
$aa->AddNullAt(-1);
$aa->AddNumberAt(-1, '1080.25');

// Get the "fruit" array
$aFruit = new JsonArray();
$json->ArrayAt2(0, $aFruit);

// Get the 1st element:
$appleObj = new JsonObject();
$aFruit->ObjectAt2(0, $appleObj);

// Modify values by member name:
$appleObj->SetStringOf('fruit', 'fuji_apple');
$appleObj->SetIntOf('count', 46);
$appleObj->SetBoolOf('fresh', false);
$appleObj->SetStringOf('extraInfo', 'developed by growers at the Tohoku Research Station in Fujisaki');

// Modify values by index:

$pearObj = new JsonObject();
$aFruit->ObjectAt2(1, $pearObj);

$pearObj->SetStringAt(0, 'bartlett_pear');
$pearObj->SetIntAt(1, 12);
$pearObj->SetBoolAt(2, false);
$pearObj->SetStringAt(3, 'harvested in late August to early September');

$json->EmitCompact = false;
echo $json->Emit(), "\n";