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

38 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 nbformat.notebooknode import from_dict 

10 

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

12 

13 

14class BytesEncoder(json.JSONEncoder): 

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

16 

17 def default(self, obj): 

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

19 if isinstance(obj, bytes): 

20 return obj.decode("ascii") 

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

22 

23 

24class JSONReader(NotebookReader): 

25 """A JSON notebook reader.""" 

26 

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

28 """Read a JSON string into a Notebook object""" 

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

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

31 return nb 

32 

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

34 """Convert a disk-format notebook dict to in-memory NotebookNode 

35 

36 handles multi-line values as strings, scrubbing of transient values, etc. 

37 """ 

38 nb = from_dict(d) 

39 nb = rejoin_lines(nb) 

40 nb = strip_transient(nb) 

41 return nb 

42 

43 

44class JSONWriter(NotebookWriter): 

45 """A JSON notebook writer.""" 

46 

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

48 """Serialize a NotebookNode object as a JSON string""" 

49 kwargs["cls"] = BytesEncoder 

50 kwargs["indent"] = 1 

51 kwargs["sort_keys"] = True 

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

53 kwargs.setdefault("ensure_ascii", False) 

54 # don't modify in-memory dict 

55 nb = copy.deepcopy(nb) 

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

57 nb = split_lines(nb) 

58 nb = strip_transient(nb) 

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

60 

61 

62_reader = JSONReader() 

63_writer = JSONWriter() 

64 

65reads = _reader.reads 

66read = _reader.read 

67to_notebook = _reader.to_notebook 

68write = _writer.write 

69writes = _writer.writes