Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.8/site-packages/nbformat/v2/nbjson.py: 58%

31 statements  

« prev     ^ index     » next       coverage.py v7.2.7, created at 2023-07-01 06:54 +0000

1"""Read and write notebooks in JSON format. 

2 

3Authors: 

4 

5* Brian Granger 

6""" 

7 

8# ----------------------------------------------------------------------------- 

9# Copyright (C) 2008-2011 The IPython Development Team 

10# 

11# Distributed under the terms of the BSD License. The full license is in 

12# the file LICENSE, distributed as part of this software. 

13# ----------------------------------------------------------------------------- 

14 

15# ----------------------------------------------------------------------------- 

16# Imports 

17# ----------------------------------------------------------------------------- 

18 

19import copy 

20import json 

21 

22from .nbbase import from_dict 

23from .rwbase import NotebookReader, NotebookWriter, rejoin_lines, restore_bytes, split_lines 

24 

25# ----------------------------------------------------------------------------- 

26# Code 

27# ----------------------------------------------------------------------------- 

28 

29 

30class BytesEncoder(json.JSONEncoder): 

31 """A JSON encoder that accepts b64 (and other *ascii*) bytestrings.""" 

32 

33 def default(self, obj): 

34 """The default value of an object.""" 

35 if isinstance(obj, bytes): 

36 return obj.decode("ascii") 

37 return json.JSONEncoder.default(self, obj) 

38 

39 

40class JSONReader(NotebookReader): 

41 """A JSON notebook reader.""" 

42 

43 def reads(self, s, **kwargs): 

44 """Convert a string to a notebook.""" 

45 nb = json.loads(s, **kwargs) 

46 nb = self.to_notebook(nb, **kwargs) 

47 return nb 

48 

49 def to_notebook(self, d, **kwargs): 

50 """Convert a string to a notebook.""" 

51 return restore_bytes(rejoin_lines(from_dict(d))) 

52 

53 

54class JSONWriter(NotebookWriter): 

55 """A JSON notebook writer.""" 

56 

57 def writes(self, nb, **kwargs): 

58 """Convert a notebook object to a string.""" 

59 kwargs["cls"] = BytesEncoder 

60 kwargs["indent"] = 1 

61 kwargs["sort_keys"] = True 

62 if kwargs.pop("split_lines", True): 

63 nb = split_lines(copy.deepcopy(nb)) 

64 return json.dumps(nb, **kwargs) 

65 

66 

67_reader = JSONReader() 

68_writer = JSONWriter() 

69 

70reads = _reader.reads 

71read = _reader.read 

72to_notebook = _reader.to_notebook 

73write = _writer.write 

74writes = _writer.writes