Skip to content

Instantly share code, notes, and snippets.

@nadersoliman
Last active August 29, 2015 14:04
Show Gist options
  • Save nadersoliman/d82368a3c80fc3efd86f to your computer and use it in GitHub Desktop.
Save nadersoliman/d82368a3c80fc3efd86f to your computer and use it in GitHub Desktop.
Converts a JSON object to tabular dictionary for easy <table> display using AngularJS
# TODO: nsoliman 20140704 should we move these functions to the frontend instead?
def json_list_to_table(json_list):
"""
Converts a list of json string to table structure, see :func: _dict_list_to_table
:param json_list:
:return:
"""
return dict_list_to_table([json.loads(item) for item in json_list])
def dict_list_to_table(dict_list):
"""
converts dict_list to a table structure, table structure is simply
a dictionary with two keys, columns: these are the collective keys
of all dictionary items. rows: these are the dictionary items themselves.
This structure is helpful client side to build html table out of list of
json string
:param dict_list:
:return: {'columns':['c1', 'c2', ...], 'rows':[{}, {}, ...]}
"""
columns = set()
for item in dict_list:
columns.update(item.keys())
return {'columns': list(columns), 'rows': dict_list}
"""
<div ng-show="dataset.tabular_samples" class="ds_sample_table">
<h3>Sample Data <small>(UI Sample #4)</small></h3>
<table>
<thead>
<tr>
<th ng-repeat="column in dataset.tabular_samples.columns"><div>{{column}}</div></th>
</tr>
</thead>
<tbody>
<tr ng-repeat="row in dataset.tabular_samples.rows">
<td ng-repeat="column in dataset.tabular_samples.columns"><div>{{row[column]}}</div></td>
</tr>
</tbody>
</table>
</div>
"""
"""
class UtilsTestCase(unittest.TestCase):
def test_dict_list_to_table(self):
table = dict_list_to_table([{'C1': '11', 'C2': '12', 'C4': '13'},
{'C1': '21', 'C2': '22', 'C3': '23'}])
self.assertEqual(set(table['columns']), set(['C1', 'C2', 'C3', 'C4']))
self.assertEqual(table['rows'], [{'C1': '11', 'C2': '12', 'C4': '13'},
{'C1': '21', 'C2': '22', 'C3': '23'}])
def test_json_list_to_table(self):
table = json_list_to_table([json.dumps({'C1': '11', 'C2': '12', 'C4': '13'}),
json.dumps({'C1': '21', 'C2': '22', 'C3': '23'})])
self.assertEqual(set(table['columns']), set(['C1', 'C2', 'C3', 'C4']))
self.assertEqual(table['rows'], [{'C1': '11', 'C2': '12', 'C4': '13'},
{'C1': '21', 'C2': '22', 'C3': '23'}])
"""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment