Jsonq
A PHP query builder for JSON
Install / Use
/learn @nahid/JsonqREADME
php-jsonq
JsonQ is a simple, elegant PHP package to Query over any type of JSON Data. It'll make your life easier by giving the flavour of an ORM-like query on your JSON.
Support For This Project
Hey due, please help me out for daily improve this project
NOTE
From the version JsonQ 6.0 all the features rewrite from QAarray. After a long run we noticed that Query Engine of JsonQ should be seperate. Becouse people want to query over various types of data like CSV, YAML, XML. So if we keep the query engine tightly coupled with this project its make no sense. Thats why we move the Query Engine part and develop a new package QAarray. Qarray is designed for queryng over native PHP array and anyone can implement their own Engine, like JsonQ.
Please do not update to >= 6.0 version directly from bellow
Installation
composer require nahid/jsonq
Usage
You can start using this package right away by importing your JSON data from a file:
use Nahid/JsonQ/Jsonq;
$jsonq = new Jsonq('data.json');
Or from a JSON String:
$json->json('{"id": 1, "name": "Nahid"}');
Or from a PHP Array:
$json->collect(['id'=>1, 'name'=>'Nahid']);
You can start Query your data using the various query methods such as find, where, orWhere, whereIn, whereStartsWith, whereEndsWith, whereContains and so on. Also you can aggregate your data after query using sum, count, groupBy, max, min etc.
Let's see a quick example:
//data.json
{
"name": "products",
"description": "Features product list",
"vendor":{
"name": "Computer Source BD",
"email": "info@example.com",
"website":"www.example.com"
},
"users":[
{"id":1, "name":"Johura Akter Sumi", "location": "Barisal"},
{"id":2, "name":"Mehedi Hasan Nahid", "location": "Barisal"},
{"id":3, "name":"Ariful Islam", "location": "Barisal"},
{"id":4, "name":"Suhel Ahmed", "location": "Sylhet"},
{"id":5, "name":"Firoz Serniabat", "location": "Gournodi"},
{"id":6, "name":"Musa Jewel", "location": "Barisal", "visits": [
{"name": "Sylhet", "year": 2011},
{"name": "Cox's Bazar", "year": 2012},
{"name": "Bandarbar", "year": 2014}
]}
],
"products": [
{"id":1, "user_id": 2, "city": "bsl", "name":"iPhone", "cat":1, "price": 80000},
{"id":2, "user_id": 2, "city": null, "name":"macbook pro", "cat": 2, "price": 150000},
{"id":3, "user_id": 2, "city": "dhk", "name":"Redmi 3S Prime", "cat": 1, "price": 12000},
{"id":4, "user_id": 1, "city": null, "name":"Redmi 4X", "cat":1, "price": 15000},
{"id":5, "user_id": 1, "city": "bsl", "name":"macbook air", "cat": 2, "price": 110000},
{"id":6, "user_id": 2, "city": null, "name":"macbook air 1", "cat": 2, "price": 81000}
]
}
use Nahid\JsonQ\Jsonq;
$q = new Jsonq('data.json');
$res = $q->from('products')
->where('cat', '=', 2)
->get();
dump($res);
//This will print
/*
array:3 [▼
1 => {#7 ▼
+"id": 2
+"user_id": 2
+"city": null
+"name": "macbook pro"
+"cat": 2
+"price": 150000
}
4 => {#8 ▼
+"id": 5
+"user_id": 1
+"city": "bsl"
+"name": "macbook air"
+"cat": 2
+"price": 110000
}
5 => {#9 ▼
+"id": 6
+"user_id": 2
+"city": null
+"name": "macbook air 1"
+"cat": 2
+"price": 81000
}
]
*/
Let's say we want to get the Summation of price of the Queried result. We can do it easily by calling the sum() method instead of get():
$result = $json->from('products')
->where('cat', '=', 2)
->sum('price');
dump($result);
//It will print:
/*
365000
*/
Pretty neat, huh?
Let's explore the full API to see what else magic this library can do for you. Shall we?
API
Following API examples are shown based on the sample JSON data given here. To get a better idea of the examples see that JSON data first. Also detailed examples of each API can be found here.
List of API:
- at
- avg
- chunk
- collect
- column
- copy
- count
- each
- except
- exists
- fetch
- filter
- find
- first
- from
- groupBy
- implode
- import
- json
- keys
- last
- macro
- max
- min
- nth
- orWhere
- pipe
- reset
- select
- size
- sort
- sortBy
- sum
- then
- toJson
- transform
- values
- where
- whereContains
- whereEndsWith
- whereIn
- whereMatch
- whereNotIn
- whereNull
- whereNotNull
- whereStartsWith
fetch()
This method will execute queries and will return the resulted data. You need to call it finally after using some query methods. Details can be found in other API examples.
find(path)
path-- the path hierarchy of the data you want to find.
You don't need to call fetch() method after this. Because this method will fetch and return the data by itself.
caveat: You can't chain further query methods after it. If you need that, you should use at() or from() method.
example:
Let's say you want to get the value of 'cities' property of your Json Data. You can do it like this:
$q = new Jsonq('data.json');
echo $q->find('vendor.name');
If you want to traverse to more deep in hierarchy, you can do it like:
$q = new Jsonq('data.json');
echo $q->find('vendor.name');
See a detail example here.
from(path)
path(optional) -- the path hierarchy of the data you want to start query from.
By default, query would be started from the root of the JSON Data you've given. If you want to first move to a nested path hierarchy of the data from where you want to start your query, you would use this method. Skipping the path parameter or giving '.' as parameter will also start query from the root Data.
Difference between this method and find() is that, find() method will return the data from the given path hierarchy. On the other hand, this method will return the Object instance, so that you can further chain query methods after it.
example:
Let's say you want to start query over the values of 'vendor.name' property of your JSON Data. You can do it like this:
$q = new Jsonq('data.json');
echo $q->from('vendor.name')->get();
If you want to traverse to more deep in hierarchy, you can do it like:
$q = new Jsonq('data.json');
echo $q->from('users.5.visits')->get();
See a detail example here.
at(path)
This is an alias method of from() and will behave exactly like that. See example here.
where(key, condition, val)
-
key-- the property name of the data. Or you can pass a Function here to group multiple query inside it. See details in example -
val-- value to be matched with. It can be a int, string, bool or even Function - depending on theop. -
op-- operand to be used for matching. The following operands are available to use:=: For weak equality matchingeq: Same as=!=: For weak not equality matchingneq: Same as!===: For strict equality matchingseq: Same as==!==: For strict not equality matchingsneq: Same as!==>: Check if value of given key in data is Greater than valgt: Same as><: Check if value of given key in data is Less than vallt: Same as<>=: Check if value of given key in data is Greater than or Equal of valgte: Same as>=<=: Check if value of given key in data is Less than or Equal of vallte: Same as<=null: Check if the value of given key in data is null (valparameter inwhere()can be omitted for thisop)notnull: Check if the value of given key in data is not null (valparameter inwhere()can be omitted for thisop)in: Check if the value of given key in data is exists in given val. val should be a plain Array.notin: Check if the value of given key in data is not exists in given val. val should be a plain Array.startswith: Check if the value of given key in data starts with (has a prefix of) the given val. This would only works for String type data.endswith: Check if the value of given key in data ends with (has a suffix of) the given val. This would only works for String type data.contains: Check if the value of given key in data has a substring of given val. This would only works for String type data.match: Check if the value of given key in data has a Regular Expression match with the given val. Thevalparameter should be a RegExp for thisop.macro: It would try to match the value of given key in data executing the givenval. Thevalparameter should be a Function for thisop. This function should have a matching logic inside it and return true or false based on that.
example:
Let's say you want to find the 'users' who has id of 1. You can do it like this:
Related Skills
node-connect
343.1kDiagnose OpenClaw node connection and pairing failures for Android, iOS, and macOS companion apps
frontend-design
90.0kCreate distinctive, production-grade frontend interfaces with high design quality. Use this skill when the user asks to build web components, pages, or applications. Generates creative, polished code that avoids generic AI aesthetics.
openai-whisper-api
343.1kTranscribe audio via OpenAI Audio Transcriptions API (Whisper).
qqbot-media
343.1kQQBot 富媒体收发能力。使用 <qqmedia> 标签,系统根据文件扩展名自动识别类型(图片/语音/视频/文件)。
