def test_partial_serialization_on_error(self): io = StringIO() try: jsonlib.dump([object()], io) except UnknownSerializerError: pass self.assertEqual(io.getvalue(), '[')
def test_fixed_truncation_error(self): data = [{"a": 3}] * 270 fp = io.StringIO() jsonlib.dump(data, fp, encoding=None) self.assertEqual(len(read(fp.getvalue())), len(data)) self.assertEqual(len(read(write(data))), len(data))
def test_no_encoding_full_unicode(self): io = StringIO() value = jsonlib.dump([u"\u24CA"], io, encoding=None, ascii_only=False) self.assertEqual(io.getvalue(), u'["\u24ca"]') self.assertEqual(type(io.getvalue()), unicode)
def test_no_encoding(self): io = StringIO() value = jsonlib.dump([u"\u24CA"], io, encoding=None) self.assertEqual(io.getvalue(), u'["\\u24ca"]') self.assertEqual(type(io.getvalue()), unicode)
def test_encode_utf16_specialcased(self): # Test that special cases that return pure ASCII are still # re-encoded if needed. io = StringIO() value = jsonlib.dump([], io, encoding='utf-16-le') self.assertEqual(io.getvalue(), '[\x00]\x00')
def test_serialize_complex_to_stream(self): io = StringIO() jsonlib.dump(["a", "b", u"c \U0001D11E \u24Ca", {"a": "b"}], io) self.assertEqual(io.getvalue(), '["a","b","c \\ud834\\udd1e \\u24ca",{"a":"b"}]')
def test_serialize_to_stream(self): io = StringIO() jsonlib.dump([], io) self.assertEqual(io.getvalue(), '[]')
""" 如果你要处理的是文件而不是字符串,你可以使用 json.dump() 和 json.load() 来编码和解码JSON数据。例如 """ import jsonlib # 写入文件 data = { 'no': 1, 'name': 'Runoob', 'url': 'http://runoob.txt.com' } with open('data.json', 'w') as f: jsonlib.dump(data, f) # 读取数据 with open('data.json', 'r') as f: data = jsonlib.loads(f)