Skip to content

Commit 7473055

Browse files
authored
Merge pull request #92 from nmarley/sort-json-keys
sort keys when serializing objects to JSON
2 parents 7c16cc6 + 08d64c6 commit 7473055

File tree

3 files changed

+16
-2
lines changed

3 files changed

+16
-2
lines changed

ipfsapi/encoding.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -277,7 +277,8 @@ def encode(self, obj):
277277
bytes
278278
"""
279279
try:
280-
result = json.dumps(obj)
280+
result = json.dumps(obj, sort_keys=True, indent=None,
281+
separators=(',', ':'))
281282
if isinstance(result, six.text_type):
282283
return result.encode("utf-8")
283284
else:

test/functional/tests.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -216,6 +216,19 @@ def test_add_recursive(self):
216216
sorted(res,
217217
key=lambda x: x['Name']))
218218

219+
def test_add_json(self):
220+
data = {'Action': 'Open', 'Type': 'PR', 'Name': 'IPFS', 'Pubkey': 7}
221+
res = self.api.add_json(data)
222+
self.assertEqual(data,
223+
self.api.get_json(res))
224+
225+
# have to test the string added to IPFS, deserializing JSON will not
226+
# test order of keys
227+
self.assertEqual(
228+
'{"Action":"Open","Name":"IPFS","Pubkey":7,"Type":"PR"}',
229+
self.api.cat(res).decode('utf-8')
230+
)
231+
219232
def test_add_get_pyobject(self):
220233
data = [-1, 3.14, u'Hän€', b'23' ]
221234
res = self.api.add_pyobj(data)

test/unit/test_encoding.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -107,7 +107,7 @@ def test_json_parse_chained_newlines(self):
107107
def test_json_encode(self):
108108
"""Tests serilization of json formatted string into an object."""
109109
data = {'key': 'value'}
110-
assert self.encoder_json.encode(data) == b'{"key": "value"}'
110+
assert self.encoder_json.encode(data) == b'{"key":"value"}'
111111

112112
def test_encode_pickle(self):
113113
"""Tests serilization of pickle formatted string into an object."""

0 commit comments

Comments
 (0)