Skip to content

ENH: IO interfaces to JSON files #1020

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 15 commits into from
Feb 9, 2015
Merged
Show file tree
Hide file tree
Changes from 12 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGES
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
Next release
============

* ENH: New io interfaces for JSON files reading/writing (https://github.com/nipy/nipype/pull/1020)
* ENH: Updated N4BiasCorrection input spec to include weight image and spline order. Made
argument formatting consistent. Cleaned ants.segmentation according to PEP8.
(https://github.com/nipy/nipype/pull/990/files)
Expand Down
101 changes: 101 additions & 0 deletions nipype/interfaces/io.py
Original file line number Diff line number Diff line change
Expand Up @@ -1801,3 +1801,104 @@ def _get_ssh_client(self):
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(host['hostname'], username=host['user'], sock=proxy)
return client


class JSONFileGrabberInputSpec(DynamicTraitedSpec, BaseInterfaceInputSpec):
in_file = File(exists=True, mandatory=True,
desc='JSON source file')


class JSONFileGrabber(IOBase):

"""
Datagrabber interface that loads a json file and generates an output for
every first-level object

Example
-------

>>> from nipype.interfaces.io import JSONFileGrabber
>>> jsonSource = JSONFileGrabber()
>>> jsonSource.inputs.in_file = 'jsongrabber.txt'
>>> res = jsonSource.run()
>>> print res.outputs.param1
exampleStr
>>> print res.outputs.param2
4

"""
input_spec = JSONFileGrabberInputSpec
output_spec = DynamicTraitedSpec
_always_run = True

def _list_outputs(self):
import json

with open(self.inputs.in_file, 'r') as f:
data = json.load(f)

if not isinstance(data, dict):
raise RuntimeError('JSON input has no dictionary structure')

outputs = {}
for key, value in data.iteritems():
outputs[key] = value

return outputs


class JSONFileSinkInputSpec(DynamicTraitedSpec, BaseInterfaceInputSpec):
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

how about adding an input that accepts a dictionary?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sorry @satra, I don't understand what you mean :S.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

something like in_dict = Dict(desc='input JSON dictionary')

so that you can pass a dictionary output of another node directly into the jsonsink node? and it will populate the relevant fields.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ok I see 👍

out_file = File(desc='JSON sink file')


class JSONFileSinkOutputSpec(TraitedSpec):
out_file = File(desc='JSON sink file')


class JSONFileSink(IOBase):

""" Very simple frontend for storing values into a JSON file.

.. warning::

This is not a thread-safe node because it can write to a common
shared location. It will not complain when it overwrites a file.

Examples
--------

>>> jsonsink = JSONFileSink(input_names=['subject_id',
... 'some_measurement'])
>>> jsonsink.inputs.subject_id = 's1'
>>> jsonsink.inputs.some_measurement = 11.4
>>> jsonsink.run() # doctest: +SKIP

"""
input_spec = JSONFileSinkInputSpec
output_spec = JSONFileSinkOutputSpec

def __init__(self, input_names, **inputs):
super(JSONFileSink, self).__init__(**inputs)
self._input_names = filename_to_list(input_names)
add_traits(self.inputs, [name for name in self._input_names])

def _list_outputs(self):
import json
import os.path as op
if not isdefined(self.inputs.out_file):
out_file = op.abspath('datasink.json')
else:
out_file = self.inputs.out_file

out_dict = dict()
for name in self._input_names:
val = getattr(self.inputs, name)
val = val if isdefined(val) else 'undefined'
out_dict[name] = val

with open(out_file, 'w') as f:
json.dump(out_dict, f)
outputs = self.output_spec().get()
outputs['out_file'] = out_file
return outputs

25 changes: 25 additions & 0 deletions nipype/interfaces/tests/test_auto_JSONFileGrabber.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
# AUTO-GENERATED by tools/checkspecs.py - DO NOT EDIT
from nipype.testing import assert_equal
from nipype.interfaces.io import JSONFileGrabber

def test_JSONFileGrabber_inputs():
input_map = dict(ignore_exception=dict(nohash=True,
usedefault=True,
),
in_file=dict(mandatory=True,
),
)
inputs = JSONFileGrabber.input_spec()

for key, metadata in input_map.items():
for metakey, value in metadata.items():
yield assert_equal, getattr(inputs.traits()[key], metakey), value

def test_JSONFileGrabber_outputs():
output_map = dict()
outputs = JSONFileGrabber.output_spec()

for key, metadata in output_map.items():
for metakey, value in metadata.items():
yield assert_equal, getattr(outputs.traits()[key], metakey), value

25 changes: 25 additions & 0 deletions nipype/interfaces/tests/test_auto_JSONFileSink.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
# AUTO-GENERATED by tools/checkspecs.py - DO NOT EDIT
from nipype.testing import assert_equal
from nipype.interfaces.io import JSONFileSink

def test_JSONFileSink_inputs():
input_map = dict(ignore_exception=dict(nohash=True,
usedefault=True,
),
out_file=dict(),
)
inputs = JSONFileSink.input_spec()

for key, metadata in input_map.items():
for metakey, value in metadata.items():
yield assert_equal, getattr(inputs.traits()[key], metakey), value

def test_JSONFileSink_outputs():
output_map = dict(out_file=dict(),
)
outputs = JSONFileSink.output_spec()

for key, metadata in output_map.items():
for metakey, value in metadata.items():
yield assert_equal, getattr(outputs.traits()[key], metakey), value

1 change: 1 addition & 0 deletions nipype/testing/data/jsongrabber.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{"param2": 4, "param1": "exampleStr"}