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

JSON: Miscellaneous Operations

See more JSON Examples

Demonstrates a variety of JSON API methods. This example uses the following JSON document:
{
   "alphabet": "abcdefghijklmnopqrstuvwxyz",
   "sampleData" : {
           "pi": 3.14,
	   "apple": "juicy",
	   "hungry": true,
	   "withoutValue": null,
           "answer": 42
          
	}
}

Chilkat PHP Downloads

Chilkat2 PHP
<?php

use Chilkat2\JsonObject;

$json = new JsonObject();
$json->EmitCompact = false;

// Assume the file contains the data as shown above..
try {
    $json->LoadFile('qa_data/json/sample2.json');
} catch (\Chilkat2\Exception $e) {
    echo $e->getMessage(), "\n";
    exit;
}

// Get the "sampleData" object:
$sampleData = new JsonObject();
$json->ObjectOf2('sampleData', $sampleData);

// Demonstrate BoolAt and BoolOf
echo 'hungry: ', ($sampleData->BoolOf('hungry') ? 'true' : 'false'), "\n";
echo 'hungry: ', ($sampleData->BoolAt(2) ? 'true' : 'false'), "\n";

// StringOf returns the value as a string regardless of it's actual type:
echo 'pi: ', $sampleData->StringOf('pi'), "\n";
echo 'answer: ', $sampleData->StringOf('answer'), "\n";
echo 'withoutValue: ', $sampleData->StringOf('withoutValue'), "\n";
echo 'hungry: ', $sampleData->StringOf('hungry'), "\n";

// Demonstrate IsNullOf / IsNullAt
echo 'withoutValue is null? ', ($sampleData->IsNullOf('withoutValue') ? 'true' : 'false'), "\n";
echo 'withoutValue is null? ', ($sampleData->IsNullAt(3) ? 'true' : 'false'), "\n";
echo 'apple is null? ', ($sampleData->IsNullOf('apple') ? 'true' : 'false'), "\n";
echo 'apple is null? ', ($sampleData->IsNullAt(1) ? 'true' : 'false'), "\n";

// IntOf
echo 'answer: ', $sampleData->IntOf('answer'), "\n";

// SetNullAt, SetNullOf
// Set "pi" to null
$sampleData->SetNullAt(0);
// Set "answer" to null
$sampleData->SetNullOf('answer');

// Show the changes:
echo $json->Emit(), "\n";

// Restore pi and apple:
$sampleData->SetNumberAt(0, '3.14');
$sampleData->SetNumberOf('answer', '42');

// Show the changes:
echo $json->Emit(), "\n";

// Add a null value named "afterApple" just after "apple"
$sampleData->AddNullAt(2, 'afterApple');

// Add a boolean value just after "pi"
$sampleData->AddBoolAt(1, 'afterPi', false);

// Examine the changes..
echo $json->Emit(), "\n";