Created
January 23, 2017 19:46
-
-
Save cgranade/b8a8839792158f3596e1355a7c5c68e7 to your computer and use it in GitHub Desktop.
maton.py: Dump MATLAB files to JSON for using with basically anything else.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
from __future__ import division, print_function | |
import click | |
import numpy as np | |
import scipy.io as sio | |
import json | |
def transform_data(data): | |
if isinstance(data, dict): | |
return { | |
key: transform_data(value) | |
for key, value in data.items() | |
} | |
elif isinstance(data, np.ndarray): | |
if data.dtype.fields: | |
return { | |
key: transform_data(data[key]) | |
for key in data.dtype.fields | |
} | |
else: | |
if data.shape == (): | |
# 0d arrays are scalars, so unpack them. | |
return transform_data(data[()]) | |
else: | |
return [ | |
transform_data(row) | |
for row in data | |
] | |
# Base case, no transformation needed. | |
return data | |
@click.command() | |
@click.argument("filename", click.Path(exists=True, dir_okay=False, file_okay=True)) | |
@click.option("--pretty", is_flag=True) | |
def main(filename, pretty): | |
data = sio.loadmat(filename, squeeze_me=True) | |
json_kwargs = { | |
'sort_keys': True, | |
'indent': 2 | |
} if pretty else {} | |
print(json.dumps(transform_data( | |
data | |
), **json_kwargs)) | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment