diff --git a/abp/fancy.py b/abp/fancy.py index a1e98a7..c5a8c3d 100644 --- a/abp/fancy.py +++ b/abp/fancy.py @@ -39,7 +39,7 @@ class GraphState(graphstate.GraphState, networkx.Graph): # Send data to browser and rate-limit try: - self.ws.send(json.dumps(self.to_json(), default = str)) + self.ws.send(json.dumps(self.to_json(stringify=True))) self.ws.recv() time.sleep(delay) except websocket._exceptions.WebSocketTimeoutException: diff --git a/abp/graphstate.py b/abp/graphstate.py index 726ab76..ac503e5 100644 --- a/abp/graphstate.py +++ b/abp/graphstate.py @@ -6,6 +6,7 @@ import itertools as it import json import qi, clifford, util import random +from util import ABPJsonEncoder class GraphState(object): @@ -177,9 +178,19 @@ class GraphState(object): nbstr = str(self.adj) return "graph:\n node: {}\n adj: {}\n".format(node, nbstr) - def to_json(self): - """ Convert the graph to JSON form """ - return {"node": self.node, "adj": self.adj} + def to_json(self, stringify = False): + """ + Convert the graph to JSON form. + JSON keys must be strings, But sometimes it is useful to have + a JSON-like object whose keys are tuples! + """ + if stringify: + node = {str(key):value for key, value in self.node.items()} + adj = {str(key): {str(key):value for key, value in ngbh.items()} + for key, ngbh in self.adj.items()} + return {"node": node, "adj": adj} + else: + return {"node": self.node, "adj": self.adj} def from_json(self, data): """ Reconstruct from JSON """ diff --git a/abp/util.py b/abp/util.py index a468b14..41378f4 100644 --- a/abp/util.py +++ b/abp/util.py @@ -2,5 +2,19 @@ Utility functions for ABP """ +import json + def xyz(x, y, z=0): return {"x": x, "y": y, "z": z} + +class ABPJsonEncoder(json.JSONEncoder): + def default(self, thing): + print thing + +if __name__ == '__main__': + j = ABPJsonEncoder() + print j.encode({1:2}) + j = ABPJsonEncoder() + print j.encode({1:2}) + print j.encode({(1,2):2}) + diff --git a/tests/test_json.py b/tests/test_json.py index 511aa4f..a3ca6a2 100644 --- a/tests/test_json.py +++ b/tests/test_json.py @@ -1,4 +1,4 @@ -from abp import GraphState +from abp import GraphState, fancy from abp import clifford from demograph import demograph import time @@ -12,11 +12,13 @@ def test_json_basic(): assert "node" in js e = GraphState() -#TODO -def _test_to_json(): - """ Nah """ - assert e != g - e.from_json(js) - assert e == g +def test_tuple_keys(): + """ Test that we can write tuple-ish keys """ + g = fancy.GraphState() + g.add_node("string") + g.add_node((1, 2, 3)) + g.add_edge((1, 2, 3), "string") + print json.dumps(g.to_json(True)) +