pax_global_header00006660000000000000000000000064137073675030014525gustar00rootroot0000000000000052 comment=a21cac30972c07c4d4879d2fd19a8ab7a75a70d8 pyjdata-0.3.6/000077500000000000000000000000001370736750300131675ustar00rootroot00000000000000pyjdata-0.3.6/.travis.yml000066400000000000000000000006361370736750300153050ustar00rootroot00000000000000os: - linux language: - python jobs: include: - python: 2.7 - python: 3.8 - python: 3.6 before_install: - if [ "$TRAVIS_OS_NAME" = "linux" ]; then sudo apt-get install python-numpy python3-numpy; fi - pip install backports.lzma addons: apt: packages: - python3-numpy - python-numpy update: true script: - python -m unittest discover -v test - python setup.py sdist pyjdata-0.3.6/LICENSE.txt000066400000000000000000000261361370736750300150220ustar00rootroot00000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. pyjdata-0.3.6/MANIFEST.in000066400000000000000000000000231370736750300147200ustar00rootroot00000000000000include README.md pyjdata-0.3.6/README.md000066400000000000000000000060341370736750300144510ustar00rootroot00000000000000# JData for Python - a lightweight and portable data annotation method - Copyright: (C) Qianqian Fang (2019-2020) - License: Apache License, Version 2.0 - Version: 0.3.6 - URL: https://github.com/fangq/pyjdata [![Build Status](https://travis-ci.com/fangq/pyjdata.svg?branch=master)](https://travis-ci.com/fangq/pyjdata) The [JData Specification](https://github.com/fangq/jdata/) defines a lightweight language-independent data annotation interface targetted at storing and sharing complex data structures across different programming languages such as MATLAB, JavaScript, Python etc. Using JData formats, a complex Python data structure can be encoded as a `dict` object that is easily serialized as a JSON/binary JSON file and share such data between programs of different languages. ## How to install * Github: download from https://github.com/fangq/pyjdata * PIP: run `pip install jdata` see https://pypi.org/project/jdata/ This package can also be installed on Ubuntu (Debian package is currently under review) via ``` sudo add-apt-repository ppa:fangq/ppa sudo apt-get update sudo apt-get install python-jdata python3-jdata ``` Dependencies: * **bjdata**: PIP: run `pip install bjdata` see https://pypi.org/project/bjdata/ * **numpy**: PIP: run `pip install numpy` or `sudo apt-get install python-numpy` * **backports.lzma**: PIP: run `pip install backports.lzma` (needed for Python 2.7) Replacing `pip` by `pip3` if you are using Python 3.x. If either `pip` or `pip3` does not exist on your system, please run ``` sudo apt-get install python-pip python3-pip ``` One can also install this module from the source code. To do this, you first check out a copy of the latest code from Github by ``` git clone https://github.com/fangq/pyjdata.git cd pyjdata ``` then install the module to your local user folder by ``` python setup.py install --user ``` or, if you prefer, install to the system folder for all users by ``` sudo python setup.py install ``` Please replace `python` by `python3` if you want to install it for Python 3.x instead of 2.x. ## How to use The PyJData module is easy to use. You can use the `encode()/decode()` functions to encode Python data into JData annotation format, or decode JData structures into native Python data, for example ``` import jdata as jd import numpy as np a={'str':'test','num':1.2,'list':[1.1,[2.1]],'nan':float('nan'),'np':np.arange(1,5,dtype=np.uint8)} jd.encode(a) jd.decode(jd.encode(a)) d1=jd.encode(a,{'compression':'zlib','base64':1}) d1 jd.decode(d1,{'base64':1}) ``` One can further save the JData annotated data into JSON or binary JSON (UBJSON) files using the `jdata.save` function, or loading JData-formatted data to Python using `jdata.load` ``` import jdata as jd import numpy as np a={'str':'test','num':1.2,'list':[1.1,[2.1]],'nan':float('nan'),'np':np.arange(1,5,dtype=np.uint8)} jd.save(a,'test.json') newdata=jd.load('test.json') newdata ``` To see additional data type support, please run the built-in test using below command ``` python -m unittest discover -v test ``` pyjdata-0.3.6/jdata/000077500000000000000000000000001370736750300142525ustar00rootroot00000000000000pyjdata-0.3.6/jdata/__init__.py000066400000000000000000000033761370736750300163740ustar00rootroot00000000000000"""pyjdata - encode and decode Python data structrues using portable JData formats This module provides an encoder and a decoder to convert a python/numpy native data structure into a JData-compatible structure, or decode JData constructs to restore python native data. import jdata as jd jdata = jd.encode(pydata) newpydata = jd.decode(jdata) jd.save(jdata,filename) jdata=jd.load(filename) The function ``encode`` converts the below python/numpy/pandas data types into JData compatible dict-based objects * python dict objects ==> unchanged (JData/JSON objects) * python string objects ==> unchanged (JData/JSON strings) * python unicode objects ==> unchanged (JData/JSON strings) * python numeric objects ==> unchanged (JData/JSON values) * python list objects ==> unchanged (JData/JSON arrays) * python tuple objects ==> unchanged (JData/JSON arrays) * python range objects ==> unchanged (JData/JSON arrays) * python bytes/bytearray objects ==> unchanged (JData/JSON bytestream) * python set objects ==> unchanged (JData/JSON arrays) * python complex numbers and complex arrays ==> JData complex array objects * numpy.ndarray objects ==> JData array objects * python tables ==> JData table objects * pandas.DataFrame objects ==> JData table objects The JData-encoded data object can then be decoded using ``decode`` to restore the original data types """ from .jfile import load, save, show, loadt, savet, loadb, saveb, jext from .jdata import encode, decode, jdtype, jsonfilter __version__ = '0.3.6' __all__ = ['load','save','show','loadt', 'savet', 'loadb', 'saveb','encode', 'decode', 'jdtype','jsonfilter','jext'] __license__ = """Apache license 2.0, Copyright (c) 2019-2020 Qianqian Fang""" if __name__ == '__main__': import cmd cmd.main() pyjdata-0.3.6/jdata/cmd.py000066400000000000000000000037441370736750300153770ustar00rootroot00000000000000"""Command line utility for pyjdata. Provides a routine for converting text-/binary-based JData files to Python data. Call python -m jdata.cmd -h to get help with command line usage. """ import argparse import os import sys from jdata import load, save def main(): # # get arguments and invoke the conversion routines # parser = argparse.ArgumentParser( description='Convert a text JData file to a binary JData file and vice versa.') parser.add_argument( 'file', nargs='+', help='path to a text-JData (.json, .jdat) file or a binary JData (.bjd, .jbat) file') parser.add_argument( '-f', '--force', action='store_const', const=True, default=False, help='overwrite existing files when converting') args = parser.parse_args() for path in args.file: spl = os.path.splitext(path) ext = spl[1].lower() if ext == '.json' or ext == '.jdat': dest = spl[0] + '.jbat' try: if os.path.exists(dest) and not args.force: raise Exception('File {} already exists.'.format(dest)) data = load(path) save(data, dest) if args.remove_input: os.remove(path) except Exception as e: print('Error: {}'.format(e)) sys.exit(1) elif ext == '.bjd' or ext == '.jbat': dest = spl[0] + '.json' try: if os.path.exists(dest) and not args.force: raise Exception('File {} already exists.'.format(dest)) data = load(path) save(data,dest) if args.remove_input: os.remove(path) except RuntimeError as e: print('Error: {}'.format(e)) sys.exit(1) else: print('Unsupported file extension on file: {}'.format(path)) sys.exit(1) if __name__ == '__main__': main() pyjdata-0.3.6/jdata/jdata.py000066400000000000000000000206071370736750300157140ustar00rootroot00000000000000"""@package docstring Encoding and decoding python native data structures as portable JData-spec annotated dict structure Copyright (c) 2019 Qianqian Fang """ __all__ = ['encode','decode','jdtype','jsonfilter'] ##==================================================================================== ## dependent libraries ##==================================================================================== import numpy as np import copy import zlib import base64 try: import lzma except ImportError: from backports import lzma ##==================================================================================== ## global variables ##==================================================================================== """ @brief Mapping Numpy data types to JData data types complex-valued data are reflected in the doubled data size """ jdtype={'float32':'single','float64':'double','float_':'double', 'bool':'uint8','byte':'int8','short':'int16','ubyte':'uint8', 'ushort':'uint16','int_':'int32','uint':'uint32','complex_':'double','complex128':'double', 'longlong':'int64','ulonglong':'uint64','csingle':'single','cdouble':'double'}; _zipper=['zlib','gzip','lzma']; ##==================================================================================== ## Python to JData encoding function ##==================================================================================== def encode(d, opt={}): """@brief Encoding a Python data structure to portable JData-annotated dict constructs This function converts complex data types (usually not JSON-serializable) into portable JData-annotated dict/list constructs that can be easily exported as JSON/JData files @param[in,out] d: an arbitrary Python data @param[in] opt: options, can contain 'compression'=['zlib','lzma','gzip'] for data compression """ if isinstance(d, float): if(np.isnan(d)): return '_NaN_'; elif(np.isinf(d)): return '_Inf_' if (d>0) else '-_Inf_'; return d; elif isinstance(d, list) or isinstance(d, tuple) or isinstance(d, set) or isinstance(d, frozenset): return encodelist(d,opt); elif isinstance(d, dict): return encodedict(d,opt); elif isinstance(d, complex): newobj={ '_ArrayType_': 'double', '_ArraySize_': 1, '_ArrayIsComplex_': True, '_ArrayData_': [d.real, d.imag] }; return newobj; elif isinstance(d, np.ndarray): newobj={}; newobj["_ArrayType_"]=jdtype[str(d.dtype)] if (str(d.dtype) in jdtype) else str(d.dtype); newobj["_ArraySize_"]=list(d.shape); if(d.dtype==np.complex64 or d.dtype==np.complex128 or d.dtype==np.csingle or d.dtype==np.cdouble): newobj['_ArrayIsComplex_']=True; newobj['_ArrayData_']=[list(d.flatten().real), list(d.flatten().imag)]; else: newobj["_ArrayData_"]=list(d.flatten()); if('compression' in opt): if(opt['compression'] not in _zipper): raise Exception('JData', 'compression method is not supported') newobj['_ArrayZipType_']=opt['compression']; newobj['_ArrayZipSize_']=[1+int('_ArrayIsComplex_' in newobj), d.size]; newobj['_ArrayZipData_']=np.asarray(newobj['_ArrayData_'],dtype=d.dtype).tostring(); if(opt['compression']=='zlib'): newobj['_ArrayZipData_']=zlib.compress(newobj['_ArrayZipData_']); elif(opt['compression']=='gzip'): newobj['_ArrayZipData_']=zlib.compress(newobj['_ArrayZipData_'],zlib.MAX_WBITS|32); elif(opt['compression']=='lzma'): newobj['_ArrayZipData_']=lzma.compress(newobj['_ArrayZipData_'],lzma.FORMAT_ALONE); if(('base64' in opt) and (opt['base64'])): newobj['_ArrayZipData_']=base64.b64encode(newobj['_ArrayZipData_']); newobj.pop('_ArrayData_'); return newobj; else: return copy.deepcopy(d); ##==================================================================================== ## JData to Python decoding function ##==================================================================================== def decode(d, opt={}): """@brief Decoding a JData-annotated dict construct into native Python data This function converts portable JData-annotated dict/list constructs back to native Python data structures @param[in,out] d: an arbitrary Python data, any JData-encoded components will be decoded @param[in] opt: options """ if (isinstance(d, str) or type(d)=='unicode') and len(d)<=6 and len(d)>4 and d[-1]=='_': if(d=='_NaN_'): return float('nan'); elif(d=='_Inf_'): return float('inf'); elif(d=='-_Inf_'): return float('-inf'); return d; elif isinstance(d, list) or isinstance(d, tuple) or isinstance(d, set) or isinstance(d, frozenset): return decodelist(d,opt); elif isinstance(d, dict): if('_ArrayType_' in d): if(isinstance(d['_ArraySize_'],str)): d['_ArraySize_']=np.array(bytearray(d['_ArraySize_'])); if('_ArrayZipData_' in d): newobj=d['_ArrayZipData_'] if(('base64' in opt) and (opt['base64'])): newobj=base64.b64decode(newobj) if('_ArrayZipType_' in d and d['_ArrayZipType_'] not in _zipper): raise Exception('JData', 'compression method is not supported') if(d['_ArrayZipType_']=='zlib'): newobj=zlib.decompress(bytes(newobj)) elif(d['_ArrayZipType_']=='gzip'): newobj=zlib.decompress(bytes(newobj),zlib.MAX_WBITS|32) elif(d['_ArrayZipType_']=='lzma'): newobj=lzma.decompress(bytes(newobj),lzma.FORMAT_ALONE) newobj=np.fromstring(newobj,dtype=np.dtype(d['_ArrayType_'])).reshape(d['_ArrayZipSize_']); if('_ArrayIsComplex_' in d and newobj.shape[0]==2): newobj=newobj[0]+1j*newobj[1]; newobj=newobj.reshape(list(d['_ArraySize_'])); return newobj; elif('_ArrayData_' in d): if(isinstance(d['_ArrayData_'],str)): newobj=np.frombuffer(d['_ArrayData_'],dtype=np.dtype(d['_ArrayType_'])); else: newobj=np.asarray(d['_ArrayData_'],dtype=np.dtype(d['_ArrayType_'])); if('_ArrayZipSize_' in d and newobj.shape[0]==1): if(isinstance(d['_ArrayZipSize_'],str)): d['_ArrayZipSize_']=np.array(bytearray(d['_ArrayZipSize_'])); newobj=newobj.reshape(d['_ArrayZipSize_']); if('_ArrayIsComplex_' in d and newobj.shape[0]==2): newobj=newobj[0]+1j*newobj[1]; newobj=newobj.reshape(d['_ArraySize_']); return newobj; else: raise Exception('JData', 'one and only one of _ArrayData_ or _ArrayZipData_ is required') return decodedict(d,opt); else: return copy.deepcopy(d); ##==================================================================================== ## helper functions ##==================================================================================== def jsonfilter(obj): if type(obj) == 'long': return str(obj) elif type(obj).__module__ == np.__name__: if isinstance(obj, np.ndarray): return obj.tolist() else: return obj.item() elif isinstance(obj, float): if(np.isnan(obj)): return '_NaN_'; elif(np.isinf(obj)): return '_Inf_' if (obj>0) else '-_Inf_'; def encodedict(d0, opt={}): d=dict(d0); for k, v in d0.items(): newkey=encode(k,opt) d[newkey]=encode(v,opt); if(k!=newkey): d.pop(k) return d; def encodelist(d0, opt={}): d=copy.deepcopy(d0) for i, s in enumerate(d): d[i] = encode(s,opt); return d; def decodedict(d0, opt={}): d=dict(d0); for k, v in d.items(): newkey=encode(k,opt) d[newkey]=decode(v,opt); if(k!=newkey): d.pop(k) return d; def decodelist(d0, opt={}): d=copy.deepcopy(d0) for i, s in enumerate(d): d[i] = decode(s,opt); return d; pyjdata-0.3.6/jdata/jfile.py000066400000000000000000000141101370736750300157120ustar00rootroot00000000000000"""@package docstring File IO to load/decode JData-based files to Python data or encode/save Python data to JData files Copyright (c) 2019 Qianqian Fang """ __all__ = ['load','save','show','loadt','savet','loadb','saveb','jext'] ##==================================================================================== ## dependent libraries ##==================================================================================== import json import os import jdata as jd from collections import OrderedDict ##==================================================================================== ## global variables ##==================================================================================== jext={'t':['.json','.jdt','.jdat','.jnii','.jmsh','.jnirs'], 'b':['.ubj','.bjd','.jdb','.jbat','.bnii','.bmsh','.jamm','.bnirs']}; ##==================================================================================== ## Loading and saving data based on file extensions ##==================================================================================== def load(fname, opt={}, **kwargs): """@brief Loading a JData file (binary or text) according to the file extension @param[in] fname: a JData file name (accept .json,.jdat,.jbat,.jnii,.bnii,.jmsh,.bmsh) @param[in] opt: options, if opt['decode']=True or 1 (default), call jdata.decode() after loading """ spl = os.path.splitext(fname) ext = spl[1].lower() if(ext in jext['t']): return loadt(fname, opt, **kwargs); elif(ext in jext['b']): return loadb(fname, opt, **kwargs); else: raise Exception('JData', 'file extension is not recognized, accept (.json,.jdat,.jbat,.jnii,.bnii,.jmsh,.bmsh)') def save(data, fname, opt={}, **kwargs): """@brief Saving Python data to file (binary or text) according to the file extension @param[in] data: data to be saved @param[in] fname: a JData file name @param[in] opt: options, if opt['encode']=True or 1 (default), call jdata.encode() before saving """ spl = os.path.splitext(fname) ext = spl[1].lower() if(ext in jext['t']): savet(data, fname, opt, **kwargs); elif(ext in jext['b']): saveb(data, fname, opt, **kwargs); else: raise Exception('JData', 'file extension is not recognized, accept (.json,.jdat,.jbat,.jnii,.bnii,.jmsh,.bmsh)') ##==================================================================================== ## Loading and saving text-based JData (i.e. JSON) files ##==================================================================================== def loadt(fname, opt={}, **kwargs): """@brief Loading a text-based (JSON) JData file and decode it to native Python data @param[in] fname: a text JData (JSON based) file name @param[in] opt: options, if opt['decode']=True or 1 (default), call jdata.decode() after loading """ kwargs.setdefault('strict',False); kwargs.setdefault('object_pairs_hook',OrderedDict); opt.setdefault('decode',True); opt['base64']=True; with open(fname, "r") as fid: data=json.load(fid, **kwargs); if(opt['decode']): data=jd.decode(data,opt); return data def savet(data, fname, opt={}, **kwargs): """@brief Saving a Python data structure to a text-based JData (JSON) file @param[in] data: data to be saved @param[in] fname: a text JData (JSON based) file name @param[in] opt: options, if opt['encode']=True or 1 (default), call jdata.encode() before saving """ kwargs.setdefault('default',jd.jsonfilter); opt.setdefault('encode',True); if(opt['encode']): data=jd.encode(data,opt); with open(fname, "w") as fid: json.dump(data, fid, **kwargs); def show(data, opt={}, **kwargs): """@brief Printing a python data as JSON string or return the JSON string (opt['string']=True) @param[in] data: data to be saved @param[in] opt: options, if opt['encode']=True or 1 (default), call jdata.encode() before printing """ kwargs.setdefault('default',jd.jsonfilter); opt.setdefault('string',False); opt.setdefault('encode',True); if(opt['encode']): data=jd.encode(data,opt); str=json.dumps(data, **kwargs); if(opt['string']): return str; else: print(str); ##==================================================================================== ## Loading and saving binary JData (i.e. UBJSON) files ##==================================================================================== def loadb(fname, opt={}, **kwargs): """@brief Loading a binary (BJData/UBJSON) JData file and decode it to native Python data @param[in] fname: a binary (BJData/UBJSON based) JData file name @param[in] opt: options, if opt['decode']=True or 1 (default), call jdata.decode() before saving """ opt.setdefault('decode',True) opt['base64']=False; try: import bjdata except ImportError: raise ImportError('To read/write binary JData files, you must install the bjdata module by "pip install bjdata"') else: with open(fname, "rb") as fid: data=bjdata.load(fid,**kwargs); if(opt['decode']): data=jd.decode(data,opt); return data def saveb(data, fname, opt={}, **kwargs): """@brief Saving a Python data structure to a binary JData (BJData/UBJSON) file @param[in] data: data to be saved @param[in] fname: a binary (BJData/UBJSON based) JData file name @param[in] opt: options, if opt['encode']=True or 1 (default), call jdata.encode() before saving """ opt.setdefault('encode',True) try: import bjdata except ImportError: raise ImportError('To read/write binary JData files, you must install the bjdata module by "pip install bjdata"') else: if(opt['encode']): data=jd.encode(data,opt); with open(fname, "wb") as fid: bjdata.dump(data, fid,**kwargs); ##==================================================================================== ## helper functions ##==================================================================================== pyjdata-0.3.6/setup.cfg000066400000000000000000000002111370736750300150020ustar00rootroot00000000000000[metadata] description-file = README.md [bdist_wheel] universal = 1 [nosetests] with-coverage = 1 cover-package = jdata cover-html = 1pyjdata-0.3.6/setup.py000066400000000000000000000022171370736750300147030ustar00rootroot00000000000000from setuptools import setup with open("README.md", "r") as fh: readme = fh.read() setup( name = 'jdata', packages = ['jdata'], version = '0.3.5', license='Apache license 2.0', description = 'Encoding and decoding Python data structrues using portable JData-annotated formats', long_description=readme, long_description_content_type="text/markdown", author = 'Qianqian Fang', author_email = 'fangqq@gmail.com', maintainer= 'Qianqian Fang', url = 'https://github.com/fangq/pyjdata', download_url = 'https://github.com/fangq/pyjdata/archive/v0.3.5.tar.gz', keywords = ['JSON', 'JData', 'UBJSON', 'OpenJData', 'NeuroJData', 'JNIfTI', 'Encoder', 'Decoder'], platforms="any", install_requires=[ ], classifiers=[ 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'Topic :: Software Development :: Build Tools', 'License :: OSI Approved :: Apache Software License', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6' ] ) pyjdata-0.3.6/test/000077500000000000000000000000001370736750300141465ustar00rootroot00000000000000pyjdata-0.3.6/test/testjd.py000066400000000000000000000033741370736750300160240ustar00rootroot00000000000000"""jdata.py test unit To run the test, please run import testjd testjd.run() Copyright (c) 2019 Qianqian Fang """ import unittest import jdata as jd import numpy as np import collections import json class TestModule(unittest.TestCase): def test_module(self): data=collections.OrderedDict(); data['const']=[2.0, 1, True, False, None, float('nan'), float('-inf')]; data['shortarray']=[1,2,3]; data['a_complex']=1+2.0j; data['object']=[[[1],[2],[3]],None, False]; data['a_typedarray']=np.asarray([9,9,9,9],dtype=np.uint8); data['a_ndarray']=np.arange(1,10,dtype=np.int32).reshape(3,3); data['a_biginteger']=9007199254740991; data['a_map']={ float('nan'): 'one', 2: 'two', "k": 'three' }; print('== Original Python native data ==') newdata=data.copy(); print(newdata); print('== JData-annotated data ==') print(jd.show(jd.encode(newdata),indent=4, default=jd.jsonfilter)); print('== JData-annotated data exported to JSON with zlib compression ==') newdata=data.copy(); print(jd.show(jd.encode(newdata,{'compression':'zlib','base64':True}), indent=4, default=jd.jsonfilter)); print('== Decoding a JData-encoded data and printed in JSON format ==') newdata=data.copy(); print(jd.show(jd.decode(jd.encode(newdata)), indent=4, default=jd.jsonfilter)); print('== Saving encoded data to test.json ==') jd.save(data,'test.json') print('== Loading data from test.json and decode ==') newdata=jd.load('test.json') print(jd.show(newdata, indent=4, default=jd.jsonfilter)); if __name__ == '__main__': unittest.main()