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

35 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 

3# Copyright (c) IPython Development Team. 

4# Distributed under the terms of the Modified BSD License. 

5 

6import copy 

7import json 

8 

9from .nbbase import from_dict 

10from .rwbase import NotebookReader, NotebookWriter, rejoin_lines, split_lines, strip_transient 

11 

12 

13class BytesEncoder(json.JSONEncoder): 

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

15 

16 def default(self, obj): 

17 """Get the default value of an object.""" 

18 if isinstance(obj, bytes): 

19 return obj.decode("ascii") 

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

21 

22 

23class JSONReader(NotebookReader): 

24 """A JSON notebook reader.""" 

25 

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

27 """Convert a string to a notebook.""" 

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

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

30 nb = strip_transient(nb) 

31 return nb 

32 

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

34 """Convert a dict to a notebook.""" 

35 return rejoin_lines(from_dict(d)) 

36 

37 

38class JSONWriter(NotebookWriter): 

39 """A JSON notebook writer.""" 

40 

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

42 """Convert a notebook to a string.""" 

43 kwargs["cls"] = BytesEncoder 

44 kwargs["indent"] = 1 

45 kwargs["sort_keys"] = True 

46 kwargs["separators"] = (",", ": ") 

47 nb = copy.deepcopy(nb) 

48 nb = strip_transient(nb) 

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

50 nb = split_lines(nb) 

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

52 

53 

54_reader = JSONReader() 

55_writer = JSONWriter() 

56 

57reads = _reader.reads 

58read = _reader.read 

59to_notebook = _reader.to_notebook 

60write = _writer.write 

61writes = _writer.writes