{"id":17172335,"url":"https://github.com/me-shaon/js-jsonq","last_synced_at":"2025-04-13T16:12:06.277Z","repository":{"id":41377450,"uuid":"132592434","full_name":"me-shaon/js-jsonq","owner":"me-shaon","description":"A simple Javascript Library to Query over Json Data","archived":false,"fork":false,"pushed_at":"2018-05-15T17:32:48.000Z","size":117,"stargazers_count":90,"open_issues_count":1,"forks_count":14,"subscribers_count":6,"default_branch":"master","last_synced_at":"2025-03-27T07:04:15.825Z","etag":null,"topics":["json","json-query","jsonq","query"],"latest_commit_sha":null,"homepage":null,"language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"cc0-1.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/me-shaon.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2018-05-08T10:23:11.000Z","updated_at":"2024-10-14T13:48:28.000Z","dependencies_parsed_at":"2022-09-19T23:10:45.764Z","dependency_job_id":null,"html_url":"https://github.com/me-shaon/js-jsonq","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/me-shaon%2Fjs-jsonq","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/me-shaon%2Fjs-jsonq/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/me-shaon%2Fjs-jsonq/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/me-shaon%2Fjs-jsonq/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/me-shaon","download_url":"https://codeload.github.com/me-shaon/js-jsonq/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248631722,"owners_count":21136560,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["json","json-query","jsonq","query"],"created_at":"2024-10-14T23:36:43.787Z","updated_at":"2025-04-13T16:12:06.258Z","avatar_url":"https://github.com/me-shaon.png","language":"JavaScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# js-jsonq\n\n**js-jsonq** is a simple, elegant Javascript 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.\n\nThis package is inspired from the awesome [jsonq](https://github.com/nahid/jsonq) package.\n\n## Installation\n\n```\nnpm install js-jsonq\n```\n\nor\n\n```\nyarn add js-jsonq\n```\n\n## Usage\n\nJust import/require the package before start using it.\n\nAs a Node.js Package:\n\n```javascript\nconst jsonQ = require('js-jsonq');\n```\n\nAs a ES6 Module:\n\n```javascript\nimport jsonQ from 'js-jsonq';\n```\n\nYou can start using this package right away by importing your Json data from a file:\n\n```javascript\nnew jsonQ('data.json');\n```\n\nOr from a Json String:\n\n```javascript\nnew jsonQ('{\"id\": 1, \"name\": \"shaon\"}');\n```\n\nOr from a Json Object:\n\n```javascript\nnew jsonQ({ id: 1, name: 'shaon' });\n```\n\nYou 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.\n\nLet's see a quick example:\n\n```javascript\n// sample Json data\nconst JsonObject = {\n    products: [\n        {\n            id: 1,\n            city: 'bsl',\n            name: 'iPhone',\n            cat: 1,\n            price: 80000.5\n        },\n        {\n            id: 2,\n            city: null,\n            name: 'macbook pro',\n            cat: 1,\n            price: 150000\n        },\n        {\n            id: 3,\n            city: 'dhk',\n            name: 'Redmi 3S Prime',\n            cat: 2,\n            price: 12000\n        },\n        {\n            id: 4,\n            city: 'bsl',\n            name: 'macbook air',\n            cat: 2,\n            price: 110000\n        }\n    ]\n};\n\nconst Q = new jsonQ(JsonObject);\nconst res = Q.from('products')\n    .where('cat', '=', 2)\n    .fetch();\nconsole.log(res);\n\n//This will print\n/*\n[\n    {\n        id: 3,\n        city: 'dhk',\n        name: 'Redmi 3S Prime',\n        cat: 2,\n        price: 12000\n    },\n    {\n        id: 4,\n        city: 'bsl',\n        name: 'macbook air',\n        cat: 2,\n        price: 110000\n    }\n]\n*/\n```\n\nLet'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 **fetch()**:\n\n```Javascript\nconst res = Q.from('products')\n    .where('cat', '=', 2)\n    .sum('price');\nconsole.log(res);\n//It will print:\n/*\n122000\n*/\n```\n\nPretty neat, huh?\n\nLet's explore the full API to see what else magic this library can do for you.\nShall we?\n\n## API\n\nFollowing API examples are shown based on the sample JSON data given [here](examples/data.json). To get a better idea of the examples see that JSON data first. Also detailed examples of each API can be found [here](examples/).\n\n**List of API:**\n\n* [fetch](#fetch)\n* [find](#findpath)\n* [at](#atpath)\n* [from](#frompath)\n* [where](#wherekey-op-val)\n* [orWhere](#orwherekey-op-val)\n* [whereIn](#whereinkey-val)\n* [whereNotIn](#wherenotinkey-val)\n* [whereNull](#wherenullkey)\n* [whereNotNull](#wherenotnullkey)\n* [whereStartsWith](#wherestartswithkey-val)\n* [whereEndsWith](#whereendswithkey-val)\n* [whereContains](#wherecontainskey-val)\n* [sum](#sumproperty)\n* [count](#count)\n* [size](#size)\n* [max](#maxproperty)\n* [min](#minproperty)\n* [avg](#avgproperty)\n* [first](#first)\n* [last](#last)\n* [nth](#nthindex)\n* [exists](#exists)\n* [groupBy](#groupbyproperty)\n* [sort](#sortorder)\n* [sortBy](#sortbyproperty-order)\n* [reset](#resetdata)\n* [copy](#copy)\n* [chunk](#chunksize)\n\n### `fetch()`\n\nThis 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.\n\n### `find(path)`\n\n* `path` -- the path hierarchy of the data you want to find.\n\nYou don't need to call `fetch()` method after this. Because this method will fetch and return the data by itself.\n\n**caveat:** You can't chain further query methods after it. If you need that, you should use `at()` or `from()` method.\n\n**example:**\n\nLet's say you want to get the value of _'cities'_ property of your Json Data. You can do it like this:\n\n```Javascript\nconst Q = new jsonQ(JsonObject).find('cities');\n```\n\nIf you want to traverse to more deep in hierarchy, you can do it like:\n\n```Javascript\nconst Q = new jsonQ(JsonObject).find('cities.1.name');\n```\n\nSee a detail example [here](examples/find.js).\n\n### `at(path)`\n\n* `path` (optional) -- the path hierarchy of the data you want to start query from.\n\nBy 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.\n\nDifference 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.\n\n**example:**\n\nLet's say you want to start query over the values of _'users'_ property of your Json Data. You can do it like this:\n\n```Javascript\nconst Q = new jsonQ(JsonObject).at('users').where('id', '=', 1).fetch();\n```\n\nIf you want to traverse to more deep in hierarchy, you can do it like:\n\n```Javascript\nconst Q = new jsonQ(JsonObject).at('users.5.visits').where('year', '=', 2011).fetch();\n```\n\nSee a detail example [here](examples/at.js).\n\n### `from(path)`\n\nThis is an alias method of `at()` and will behave exactly like that. See example [here](examples/from.js).\n\n### `where(key, op, val)`\n\n* `key` -- the property name of the data. Or you can pass a Function here to group multiple query inside it. See details in [example](examples/where.js)\n* `val` -- value to be matched with. It can be a _int_, _string_, _bool_ or even _Function_ - depending on the `op`.\n* `op` -- operand to be used for matching. The following operands are available to use:\n\n    * `=` : For weak equality matching\n    * `eq` : Same as `=`\n    * `!=` : For weak not equality matching\n    * `neq` : Same as `!=`\n    * `==` : For strict equality matching\n    * `seq` : Same as `==`\n    * `!==` : For strict not equality matching\n    * `sneq` : Same as `!==`\n    * `\u003e` : Check if value of given **key** in data is Greater than **val**\n    * `gt` : Same as `\u003e`\n    * `\u003c` : Check if value of given **key** in data is Less than **val**\n    * `lt` : Same as `\u003c`\n    * `\u003e=` : Check if value of given **key** in data is Greater than or Equal of **val**\n    * `gte` : Same as `\u003e=`\n    * `\u003c=` : Check if value of given **key** in data is Less than or Equal of **val**\n    * `lte` : Same as `\u003c=`\n    * `null` : Check if the value of given **key** in data is **null** (`val` parameter in `where()` can be omitted for this `op`)\n    * `notnull` : Check if the value of given **key** in data is **not null** (`val` parameter in `where()` can be omitted for this `op`)\n    * `in` : Check if the value of given **key** in data is exists in given **val**. **val** should be a plain _Array_.\n    * `notin` : Check if the value of given **key** in data is not exists in given **val**. **val** should be a plain _Array_.\n    * `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.\n    * `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.\n    * `contains` : Check if the value of given **key** in data has a substring of given **val**. This would only works for _String_ type data.\n    * `match` : Check if the value of given **key** in data has a Regular Expression match with the given **val**. The `val` parameter should be a **RegExp** for this `op`.\n    * `macro` : It would try to match the value of given **key** in data executing the given `val`. The `val` parameter should be a **Function** for this `op`. This function should have a matching logic inside it and return **true** or **false** based on that.\n\n**example:**\n\nLet's say you want to find the _'users'_ who has _id_ of `1`. You can do it like this:\n\n```Javascript\nconst Q = new jsonQ(JsonObject).from('users').where('id', '=', 1).fetch();\n```\n\nYou can add multiple _where_ conditions. It'll give the result by AND-ing between these multiple where conditions.\n\n```Javascript\nconst Q = new jsonQ(JsonObject).from('users').where('id', '=', 1).where('location', '=', 'Sylhet').fetch();\n```\n\nSee a detail example [here](examples/where.js).\n\n### `orWhere(key, op, val)`\n\nParameters of `orWhere()` are the same as `where()`. The only difference between `where()` and `orWhere()` is: condition given by the `orWhere()` method will OR-ed the result with other conditions.\n\nFor example, if you want to find the users with _id_ of `1` or `2`, you can do it like this:\n\n```Javascript\nconst Q = new jsonQ(JsonObject).from('users').where('id', '=', 1).orWhere('id', '=', 2).fetch();\n```\n\nSee detail example [here](examples/orWhere.js).\n\n### `whereIn(key, val)`\n\n* `key` -- the property name of the data\n* `val` -- it should be an **Array**\n\nThis method will behave like `where(key, 'in', val)` method call.\n\n### `whereNotIn(key, val)`\n\n* `key` -- the property name of the data\n* `val` -- it should be an **Array**\n\nThis method will behave like `where(key, 'notin', val)` method call.\n\n### `whereNull(key)`\n\n* `key` -- the property name of the data\n\nThis method will behave like `where(key, 'null')` or `where(key, '=', null)` method call.\n\n### `whereNotNull(key)`\n\n* `key` -- the property name of the data\n\nThis method will behave like `where(key, 'notnull')` or `where(key, '!=', null)` method call.\n\n### `whereStartsWith(key, val)`\n\n* `key` -- the property name of the data\n* `val` -- it should be a String\n\nThis method will behave like `where(key, 'startswith', val)` method call.\n\n### `whereEndsWith(key, val)`\n\n* `key` -- the property name of the data\n* `val` -- it should be a String\n\nThis method will behave like `where(key, 'endswith', val)` method call.\n\n### `whereContains(key, val)`\n\n* `key` -- the property name of the data\n* `val` -- it should be a String\n\nThis method will behave like `where(key, 'contains', val)` method call.\n\n### `sum(property)`\n\n* `property` -- the property name of the data\n\n**example:**\n\nLet's say you want to find the sum of the _'price'_ of the _'products'_. You can do it like this:\n\n```Javascript\nconst Q = new jsonQ(JsonObject).from('products').sum('price').fetch();\n```\n\nIf the data you are aggregating is plain array, you don't need to pass the 'property' parameter.\nSee detail example [here](examples/sum.js)\n\n### `count()`\n\nIt will return the number of elements in the collection.\n\n**example:**\n\nLet's say you want to find how many elements are in the _'products'_ property. You can do it like:\n\n```Javascript\nconst Q = new jsonQ(JsonObject).from('products').count();\n```\n\nSee detail example [here](examples/count.js).\n\n### `size()`\n\nThis is an alias method of `count()`.\n\n### `max(property)`\n\n* `property` -- the property name of the data\n\n**example:**\n\nLet's say you want to find the maximum of the _'price'_ of the _'products'_. You can do it like this:\n\n```Javascript\nconst Q = new jsonQ(JsonObject).from('products').max('price').fetch();\n```\n\nIf the data you are querying is plain array, you don't need to pass the 'property' parameter.\nSee detail example [here](examples/max.js)\n\n### `min(property)`\n\n* `property` -- the property name of the data\n\n**example:**\n\nLet's say you want to find the minimum of the _'price'_ of the _'products'_. You can do it like this:\n\n```Javascript\nconst Q = new jsonQ(JsonObject).from('products').min('price').fetch();\n```\n\nIf the data you are querying is plain array, you don't need to pass the 'property' parameter.\nSee detail example [here](examples/min.js)\n\n### `avg(property)`\n\n* `property` -- the property name of the data\n\n**example:**\n\nLet's say you want to find the average of the _'price'_ of the _'products'_. You can do it like this:\n\n```Javascript\nconst Q = new jsonQ(JsonObject).from('products').avg('price').fetch();\n```\n\nIf the data you are querying is plain array, you don't need to pass the 'property' parameter.\nSee detail example [here](examples/avg.js)\n\n### `first()`\n\nIt will return the first element of the collection.\n\n**example:**\n\n```Javascript\nconst Q = new jsonQ(JsonObject).from('products').first();\n```\n\nSee detail example [here](examples/first.js).\n\n### `last()`\n\nIt will return the last element of the collection.\n\n**example:**\n\n```Javascript\nconst Q = new jsonQ(JsonObject).from('products').last();\n```\n\nSee detail example [here](examples/last.js).\n\n### `nth(index)`\n\n* `index` -- index of the element to be returned.\n\nIt will return the nth element of the collection. If the given index is a **positive** value, it will return the nth element from the beginning. If the given index is a **negative** value, it will return the nth element from the end.\n\n**example:**\n\n```Javascript\nconst Q = new jsonQ(JsonObject).from('products').nth(2);\n```\n\nSee detail example [here](examples/nth.js).\n\n### `exists()`\n\nIt will return **true** if the element is not **empty** or not **null** or not an **empty array** or not an **empty object**.\n\n**example:**\n\nLet's say you want to find how many elements are in the _'products'_ property. You can do it like:\n\n```Javascript\nconst Q = new jsonQ(JsonObject).from('products').count();\n```\n\nSee detail example [here](examples/exists.js).\n\n### `groupBy(property)`\n\n* `property` -- The property by which you want to group the collection.\n\n**example:**\n\nLet's say you want to group the _'users'_ data based on the _'location'_ property. You can do it like:\n\n```Javascript\nconst Q = new jsonQ(JsonObject).from('users').groupBy('location').fetch();\n```\n\nSee detail example [here](examples/groupBy.js).\n\n### `sort(order)`\n\n* `order` -- If you skip the _'order'_ property the data will be by default ordered as **ascending**. You need to pass **'desc'** as the _'order'_ parameter to sort the data in **descending** order. Also, you can pass a compare function in _'order'_ parameter to define your own logic to order the data.\n\n**Note:** This method should be used for plain Array. If you want to sort an Array of Objects you should use the **sortBy()** method described later.\n\n**example:**\n\nLet's say you want to sort the _'arr'_ data. You can do it like:\n\n```Javascript\nconst Q = new jsonQ(JsonObject).from('arr').sort().fetch();\n```\n\nSee detail example [here](examples/sort.js).\n\n### `sortBy(property, order)`\n\n* `property` -- You need to pass the property name on which the sorting will be done.\n* `order` -- If you skip the _'order'_ property the data will be by default ordered as **ascending**. You need to pass **'desc'** as the _'order'_ parameter to sort the data in **descending** order. Also, you can pass a compare function in _'order'_ parameter to define your own logic to order the data.\n\n**Note:** This method should be used for Array of Objects. If you want to sort a plain Array you should use the **sort()** method described earlier.\n\n**example:**\n\nLet's say you want to sort the _'price'_ data of _'products'_. You can do it like:\n\n```Javascript\nconst Q = new jsonQ(JsonObject).from('products').sortBy('price').fetch();\n```\n\nSee detail example [here](examples/sortBy.js).\n\n### `reset(data)`\n\n* `data` -- can be a JSON file path, or a JSON string or a JSON Object. If no data passed in the `data` parameter, the `jsonQ` Object instance will be reset to previously initialized data.\n\nAt any point, you might want to reset the Object instance to a completely different set of data and then query over it. You can use this method in that case.\n\nSee a detail example [here](examples/reset.js).\n\n### `copy()`\n\nIt will return a complete clone of the Object instance.\n\nSee a detail example [here](examples/copy.js).\n\n### `chunk(size, fn)`\n\nIt will return a complete new array after chunking your array with specific size.\nIf you want to transform each of the chunk based on any specific logic, pass a\nfunction containing that transformation as the second parameter of the `chunk()` method. \n\nSee a detail example [here](examples/chunk.js).\n\n## Bugs and Issues\n\nIf you encounter any bugs or issues, feel free to [open an issue at\ngithub](https://github.com/me-shaon/js-jsonq/issues).\n\nAlso, you can shoot me an email to\n\u003cmailto:shaon.cse81@gmail.com\u003e for hugs or bugs.\n\n## Credit\n\nSpeical thanks to [Nahid Bin Azhar](https://github.com/nahid) for the inspiration and guidance for the package.\n\n## Contributions\n\nIf your PR is successfully merged to this project, feel free to add yourself in the list of contributors.\nSee all the [contributors](CONTRIBUTORS.md).\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fme-shaon%2Fjs-jsonq","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fme-shaon%2Fjs-jsonq","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fme-shaon%2Fjs-jsonq/lists"}