PHP code example of mameyugo / jsonq
1. Go to this page and download the library: Download mameyugo/jsonq library . Choose the download type require .
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
mameyugo / jsonq example snippets
use JsonQ\Store;
// Create store
$store = new Store('data.json');
// Write data
$store->set('users', [
['id' => 1, 'name' => 'Alice', 'role' => 'admin', 'age' => 30],
['id' => 2, 'name' => 'Bob', 'role' => 'user', 'age' => 25],
['id' => 3, 'name' => 'Charlie', 'role' => 'user', 'age' => 35],
]);
// Query with MongoDB-style syntax
$admins = $store->find('users', ['role' => 'admin']);
// Returns: [['id' => 1, 'name' => 'Alice', ...]]
// Fluent query builder
$results = $store->executeQuery('users', [
'where' => [
['field' => 'age', 'op' => '>=', 'value' => 25]
],
'order_by' => ['field' => 'age', 'direction' => 'desc'],
'limit' => 10
]);
// Aggregation
$avgAge = $store->aggregate('users', ['avg' => 'age']);
// Returns: ['avg' => 30.0]
echo "✅ JsonQ is working!\n";
// Create/Update
$store->set('user.profile', ['name' => 'Alice', 'age' => 30]);
// Read
$profile = $store->get('user.profile');
// Returns: ['name' => 'Alice', 'age' => 30]
// Check existence
$exists = $store->has('user.profile'); // true
// Delete
$store->remove('user.profile');
// Count elements
$count = $store->count('users'); // 3
// Push to array
$store->push('users', ['id' => 4, 'name' => 'Dave']);
// Merge objects
$store->merge('config', ['debug' => true]);
// Increment/Decrement
$store->increment('stats.views'); // views++
$store->decrement('inventory.stock', 5); // stock -= 5
// Greater than
$adults = $store->find('users', ['age' => ['$gt' => 18]]);
// Range queries
$midAge = $store->find('users', [
'age' => ['$gte' => 25, '$lte' => 35]
]);
// Not equal
$active = $store->find('users', ['status' => ['$ne' => 'deleted']]);
// In array
$roles = $store->find('users', [
'role' => ['$in' => ['admin', 'moderator']]
]);
// Not in array
$regular = $store->find('users', [
'role' => ['$nin' => ['admin', 'guest']]
]);
// Array size
$teams = $store->find('projects', [
'members' => ['$size' => 5]
]);
// Contains substring
$gmailUsers = $store->find('users', [
'email' => ['$contains' => '@gmail.com']
]);
// Starts with
$adminUsers = $store->find('users', [
'username' => ['$startsWith' => 'admin_']
]);
// Ends with
$txtFiles = $store->find('files', [
'name' => ['$endsWith' => '.txt']
]);
// Regex matching (with ReDoS protection)
$phoneNumbers = $store->find('contacts', [
'phone' => ['$regex' => '^\+1-\d{3}-\d{3}-\d{4}$']
]);
// AND (implicit)
$seniorAdmins = $store->find('users', [
'role' => 'admin',
'age' => ['$gte' => 30]
]);
// OR
$privileged = $store->find('users', [
'$or' => [
['role' => 'admin'],
['role' => 'moderator']
]
]);
// NOT
$notGuests = $store->find('users', [
'$not' => ['role' => 'guest']
]);
// Complex nested logic
$results = $store->find('users', [
'$and' => [
['age' => ['$gte' => 18]],
['$or' => [
['role' => 'admin'],
['verified' => true]
]]
]
]);
$results = $store->executeQuery('products', [
// Filtering
'where' => [
['field' => 'price', 'op' => '>', 'value' => 100],
['field' => 'inStock', 'op' => '=', 'value' => true]
],
// Sorting
'order_by' => [
'field' => 'price',
'direction' => 'desc' // or 'asc'
],
// Pagination
'skip' => 10, // Offset
'limit' => 20, // Max results
// Projection (v0.3.0)
'select' => ['name', 'price', 'category']
]);
// Single aggregation
$total = $store->aggregate('orders', ['sum' => 'amount']);
// Returns: ['sum' => 15750.50]
// Multiple aggregations
$stats = $store->aggregate('products', [
'sum' => 'price',
'avg' => 'price',
'min' => 'price',
'max' => 'price',
'count' => 'id'
]);
// Returns: ['sum' => 5000, 'avg' => 250, 'min' => 50, 'max' => 1000, 'count' => 20]
// Group by
$byCategory = $store->groupBy('products', 'category');
// Returns: ['electronics' => [...], 'books' => [...]]
// Extract column values
$names = $store->pluck('users', 'name');
// Returns: ['Alice', 'Bob', 'Charlie']
// Select specific fields (projection)
$results = $store->executeQuery('users', [
'select' => ['name', 'email'] // Only return name and email
]);
// Extract column values
$emails = $store->column('users', 'email');
// Returns: ['[email protected] ', '[email protected] ', ...]
// Split into chunks
$chunks = $store->chunk('users', 10);
// Returns: [[user1..10], [user11..20], ...]
// Join column values
$nameList = $store->implode('users', 'name', ', ');
// Returns: "Alice, Bob, Charlie, Dave"
// Get object keys
$keys = $store->keys('user.profile');
// Returns: ['name', 'email', 'age', 'verified']
// Get object values
$values = $store->values('user.profile');
// Returns: ['Alice', '[email protected] ', 30, true]
// Serialize to JSON
$json = $store->toJson('users');
$prettyJson = $store->toJson('users', true); // Pretty-print
// Stream array items (or object properties) one by one
$users = $store->stream('/logs');
// Stream with on-the-fly MongoDB-style filtering
$errors = $store->stream('/logs',
['level' => 'error'], // Conditions
['limit' => 500, 'select' => ['message', 'timestamp']] // Options
);
// Stream directly to a new file (zero memory overhead)
$store->streamToFile('/backups', '/tmp/recent.json', ['date' => ['$gt' => '2025-01-01']]);
// Perform aggregate math over a stream
$totalSales = $store->streamAggregate('/orders', 'sum', 'amount', ['status' => 'completed']);
// Define schema
$schema = [
'type' => 'object',
'pe' => 'string',
'minLength' => 2,
'maxLength' => 50
],
'email' => [
'type' => 'string',
'format' => 'email'
],
'age' => [
'type' => 'integer',
'minimum' => 18,
'maximum' => 120
],
'role' => [
'type' => 'string',
'enum' => ['admin', 'user', 'guest']
]
]
];
// Validate single document
$user = ['name' => 'Alice', 'email' => '[email protected] ', 'age' => 30];
$isValid = $store->validate($user, $schema);
// Returns: true
// Validate collection
$result = $store->validateCollection('users', $schema);
// Returns: ['valid' => true, 'errors' => []]
// Create single-field index
$store->createIndex('users', 'email');
// Create compound index
$store->createCompoundIndex('orders', ['customerId', 'status']);
// Direct index lookup (O(1))
$user = $store->indexLookup('users', 'email', '[email protected] ');
// List all indexes
$indexes = $store->listIndexes();
// Returns: ['users.email' => 'single', 'orders.customerId+status' => 'compound']
// Drop index
$store->dropIndex('users.email');
// Drop all indexes
$store->dropAllIndexes();
try {
// Begin transaction
$store->begin();
// Perform multiple operations
$store->set('accounts.A', ['balance' => 900]);
$store->set('accounts.B', ['balance' => 1100]);
$store->set('logs', ['transfer' => 100]);
// Commit atomically
$store->commit();
echo "✅ Transaction committed\n";
} catch (Exception $e) {
// Rollback on error
$store->rollback();
echo "❌ Transaction rolled back: " . $e->getMessage() . "\n";
}
// Enable Zstd compression (best compression ratio + speed)
$store->setOption('compression', 'zstd');
// Or use Gzip
$store->setOption('compression', 'gzip');
// Disable compression
$store->setOption('compression', 'none');
// Transparent decompression - reads work automatically
$data = $store->get('users');
// Get real-time metrics
$metrics = $store->getMetrics();
echo "Reads: " . $metrics['reads'] . "\n";
echo "Writes: " . $metrics['writes'] . "\n";
echo "Cache Hits: " . $metrics['cache_hits'] . "\n";
echo "Cache Misses: " . $metrics['cache_misses'] . "\n";
echo "Hit Rate: " . $metrics['cache_hit_rate'] . "%\n";
echo "Avg Latency: " . $metrics['avg_latency_ms'] . "ms\n";
// Create backup
$store->backup('/backups/data-' . date('Y-m-d') . '.json');
// Restore from backup
$store->restore('/backups/data-2024-01-15.json');
// Get file stats
$stats = $store->stats();
echo "File size: " . $stats['file_size'] . " bytes\n";
echo "Last modified: " . $stats['modified_at'] . "\n";
// Get current config
$config = jsonq_get_config();
// Set max file size
jsonq_set_max_file_size('100M'); // or '1G', '500K'
// Set allowed extensions
jsonq_set_allowed_extensions('json,db');
// Set base path (security restriction)
jsonq_set_base_path('/var/www/data');
// Clear base path restriction
jsonq_clear_base_path();