Package: pyjsonq
py-jsonqpy-jsonqis a simple, elegant Python 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.Installationpip install pyjsonqUsageJust import the package before start using it.As a Python Package:frompyjsonqimportJsonQYou can start using this package right away by importing your Json data from a file:JsonQ('data.json')orJsonQ(data={"id":1,"name":"shaonty"})# must assign data if you want to pass data instead of file_pathYou can start Query your data using the various query methods such aswhere,or_where,where_in,where_not_in,where_starts_with,where_ends_with,where_containsand so on. Also you can aggregate your data after query usingsum,count,group_by,sort_by,max,minetc.Let's see a quick example:# sample Json datajson_object={products:[{id:1,city:'bsl',name:'iPhone',cat:1,price:80000.5},{id:2,city:null,name:'macbook pro',cat:1,price:150000},{id:3,city:'dhk',name:'Redmi 3S Prime',cat:2,price:12000},{id:4,city:'bsl',name:'macbook air',cat:2,price:110000}]};qe=JsonQ(file_path)res=qe.at('products').where('cat','=',2).get()print(res)"""This will print[{id: 3,city: 'dhk',name: 'Redmi 3S Prime',cat: 2,price: 12000},{id: 4,city: 'bsl',name: 'macbook air',cat: 2,price: 110000}]"""Let's say we want to get the Summation ofpriceof the Queried result. We can do it easily by calling thesum()method instead ofget():res=qe.at('products').where('cat','=',2).sum('price')print(res)"""It will print:122000"""Let's explore the full API to see what else magic this library can do for you.
Shall we?APIFollowing API examples are shown based on the sample JSON data givenhere. To get a better idea of the examples see that JSON data first. Also detailed examples of each API can be foundhere.List of API:getfrom_pathatwhereor_wherewhere_inwhere_not_inwhere_nullwhere_not_nullwhere_starts_withwhere_ends_withwhere_containssumcountsizemaxminavgfirstlastnthgroup_bysortsortByresetclonechunkget()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.from_file(file_path)This method is the alternative of set json file path. Details can be found in other API examples.example:Let's say you have a file nameddata.json. You can set path like this:qu=JsonQ().from_file('data.json').at('users').where('id','=',1).get()at(path)path-- 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 thepathparameter or giving'.'as parameter will also start query from the root Data.example:Let's say you want to start query over the values of'users'property of your Json Data. You can do it like this:qu=JsonQ(file_path).at('users').where('id','=',1).get()If you want to traverse to more deep in hierarchy, you can do it like:qe=JsonQ(file_path).at('users.5.visits').where('year','=',2011).get()See a detail examplehere.where(key, operator, value)key-- the property name of the data. Or you can pass a Function here to group multiple query inside it. See details inexamplevalue-- value to be matched with. It can be aint,string,boolor evenfloat- depending on theoperator.operator-- operand to be used for matching. The following operands are available to use:=: For equality matchingeq: Same as=!=: For weak not equality matchingneq: Same as!=>: Check if value of givenkeyin data is Greater thanvaluegt: Same as><: Check if value of givenkeyin data is Less thanvaluelt: Same as<>=: Check if value of givenkeyin data is Greater than or Equal ofvaluegte: Same as>=<=: Check if value of givenkeyin data is Less than or Equal ofvaluelte: Same as<=null: Check if the value of givenkeyin data isnull(valueparameter inwhere()can be omitted for thisoperator)notnull: Check if the value of givenkeyin data isnot null(valueparameter inwhere()can be omitted for thisoperator)in: Check if the value of givenkeyin data is exists in givenvalue.valueshould be a plainList.notin: Check if the value of givenkeyin data is not exists in givenval.valshould be a plainList.startswith: Check if the value of givenkeyin data starts with (has a prefix of) the givenvalue. This would only works forStringtype data.endswith: Check if the value of givenkeyin data ends with (has a suffix of) the givenvalue. This would only works forStringtype data.contains: Same asinexample:Let's say you want to find the'users'who hasidof1. You can do it like this:qu=JsonQ(file_path).at('users').where('id','=',1).get()You can add multiplewhereconditions. It'll give the result by AND-ing between these multiple where conditions.qe=JsonQ(file_path).at('users').where('id','=',1).where('location','=','Sylhet').get()See a detail examplehere.or_where(key, operator, value)Parameters ofor_where()are the same aswhere(). The only difference betweenwhere()andor_where()is: condition given by theor_where()method will OR-ed the result with other conditions.For example, if you want to find the users withidof1or2, you can do it like this:re=JsonQ(file_path).at('users').where('id','=',1).or_where('id','=',2).get()See detail examplehere.where_in(key, value)key-- the property name of the datavalue-- it should be anListThis method will behave likewhere(key, 'in', value)method call.where_not_in(key, value)key-- the property name of the datavalue-- it should be anListThis method will behave likewhere(key, 'notin', value)method call.where_null(key)key-- the property name of the dataThis method will behave likewhere(key, '=', 'None')method call.where_not_null(key)key-- the property name of the dataThis method will behave likewhere(key, '!=', 'None')method call.where_starts_with(key, value)key-- the property name of the datavalue-- it should be a StringThis method will behave likewhere(key, 'startswith', value)method call.where_ends_with(key, value)key-- the property name of the datavalue-- it should be a StringThis method will behave likewhere(key, 'endswith', value)method call.where_contains(key, val)key-- the property name of the datavalue-- it should be a String or ListThis method will behave likewhere(key, 'contains', val)method call.sum(property)property-- the property name of the dataexample:Let's say you want to find the sum of the'price'of the'products'. You can do it like this:qe=JsonQ(file_path).at('products').sum('price')If the data you are aggregating is plain list, you don't need to pass the 'property' parameter.
See detail exampleherecount()It will return the number of elements in the collection.example:Let's say you want to find how many elements are in the'products'property. You can do it like:qe=JsonQ(file_path).at('products').count()See detail examplehere.size()This is an alias method ofcount().max(property)property-- the property name of the dataexample:Let's say you want to find the maximum of the'price'of the'products'. You can do it like this:qu=JsonQ(file_path).at('products').max('price')If the data you are querying is plain array, you don't need to pass the 'property' parameter.
See detail exampleheremin(property)property-- the property name of the dataexample:Let's say you want to find the minimum of the'price'of the'products'. You can do it like this:qe=JsonQ(file_path).at('products').min('price')If the data you are querying is plain array, you don't need to pass the 'property' parameter.
See detail examplehereavg(property)property-- the property name of the dataexample:Let's say you want to find the average of the'price'of the'products'. You can do it like this:qe=JsonQ(file_path).at('products').avg('price')If the data you are querying is plain array, you don't need to pass the 'property' parameter.
See detail exampleherefirst()It will return the first element of the collection.example:qe=JsonQ(file_path).at('products').first()See detail examplehere.last()It will return the last element of the collection.example:qe=JsonQ(file_path).at('products').last()See detail examplehere.nth(index)index-- index of the element to be returned.It will return the nth(n starts from 0) element of the collection. If the given index is apositivevalue, it will return the nth element from the beginning. If the given index is anegativevalue, it will return the nth element from the end.example:qe=JsonQ(file_path).at('products').nth(2)See detail examplehere.group_by(property)property-- The property by which you want to group the collection.example:Let's say you want to group the'users'data based on the'location'property. You can do it like:qe=JsonQ(file_path).at('users').group_by('location').get()See detail examplehere.sort(order)order-- If you skip the'order'property the data will be by default ordered asascending. You need to pass'desc'as the'order'parameter to sort the data indescendingorder. Also, you can pass a compare function in'order'parameter to define your own logic to order the data.Note:This method should be used for plain Array. If you want to sort an Array of Objects you should use thesortBy()method described later.example:Let's say you want to sort the'arr'data. You can do it like:qe=JsonQ(file_path).at('arr').sort().get()See detail examplehere.sort_by(property, order)property-- You need to pass the property name on which the sorting will be done.order-- If you skip the'order'property the data will be by default ordered asascending. You need to pass'desc'as the'order'parameter to sort the data indescendingorder. Also, you can pass a compare function in'order'parameter to define your own logic to order the data.Note:This method should be used for Array of Objects. If you want to sort a plain Array you should use thesort()method described earlier.example:Let's say you want to sort the'price'data of'products'. You can do it like:qe=JsonQ(file_path).at('products').sort_by('price').get()See detail examplehere.reset(data)data-- can be a JSON file path, or a JSON string or a JSON Object. If no data passed in thedataparameter, theJsonQObject instance will be reset to previously initialised data.At 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.See a detail examplehere.clone()It will return a complete clone of the Object instance.See a detail examplehere.chunk(size)It will return a complete new array after chunking your array with specific size.See a detail examplehere.Bugs and IssuesIf you encounter any bugs or issues, feel free toopen an issue at
github.Also, you can shoot me an email tomailto:shaonty.dutta@gmail.comfor suggestion or bugs.CreditSpeical thanks toNahid Bin Azharfor the inspiration and guidance for the package.Others Platformphp-jsonqjs-jsonq