Skip to content

Commit

Permalink
Implement Tableset.to_json. Closes wireservice#374.
Browse files Browse the repository at this point in the history
  • Loading branch information
nbedi committed Dec 4, 2015
1 parent 0fdd7cc commit 99c1b25
Show file tree
Hide file tree
Showing 5 changed files with 78 additions and 1 deletion.
20 changes: 19 additions & 1 deletion agate/tableset.py
Original file line number Diff line number Diff line change
Expand Up @@ -169,7 +169,7 @@ def from_csv(cls, dir_path, column_names=None, column_types=None, row_names=None

def to_csv(self, dir_path, **kwargs):
"""
Write this each table in this set to a separate CSV in a given
Write each table in this set to a separate CSV in a given
directory.
See :meth:`.Table.to_csv` for additional details.
Expand All @@ -185,6 +185,24 @@ def to_csv(self, dir_path, **kwargs):

table.to_csv(path, **kwargs)

def to_json(self, dir_path, **kwargs):
"""
Write each table in this set to a separate JSON file in a given
directory.
See :meth:`.Table.to_json` for additional details.
:param dir_path:
Path to the directory to write the JSON files to.
"""
if not os.path.exists(dir_path):
os.makedirs(dir_path)

for name, table in self.items():
path = os.path.join(dir_path, '%s.json' % name)

table.to_json(path, **kwargs)

@property
def column_types(self):
"""
Expand Down
14 changes: 14 additions & 0 deletions examples/tableset/table1.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
[
{
"letter": "a",
"number": 1
},
{
"letter": "a",
"number": 3
},
{
"letter": "b",
"number": 2
}
]
14 changes: 14 additions & 0 deletions examples/tableset/table2.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
[
{
"letter": "b",
"number": 0
},
{
"letter": "a",
"number": 2
},
{
"letter": "c",
"number": 5
}
]
14 changes: 14 additions & 0 deletions examples/tableset/table3.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
[
{
"letter": "a",
"number": 1
},
{
"letter": "a",
"number": 2
},
{
"letter": "c",
"number": 3
}
]
17 changes: 17 additions & 0 deletions tests/test_tableset.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
from decimal import Decimal

import shutil
import json

try:
import unittest2 as unittest
Expand Down Expand Up @@ -95,6 +96,22 @@ def test_to_csv(self):

shutil.rmtree('.test-tableset')

def test_to_json(self):
tableset = TableSet(self.tables.values(), self.tables.keys())

tableset.to_json('.test-tableset')

for name in ['table1', 'table2', 'table3']:
with open('.test-tableset/%s.json' % name) as f:
contents1 = json.load(f)

with open('examples/tableset/%s.json' % name) as f:
contents2 = json.load(f)

self.assertEqual(contents1, contents2)

shutil.rmtree('.test-tableset')

def test_get_column_types(self):
tableset = TableSet(self.tables.values(), self.tables.keys())

Expand Down

0 comments on commit 99c1b25

Please sign in to comment.