graphtage.json¶
A graphtage.Filetype for parsing, diffing, and rendering JSON files.
json classes¶
JSON¶
- class graphtage.json.JSON¶
Bases:
graphtage.FiletypeThe JSON file type.
- __init__()¶
Initializes the JSON file type.
By default, JSON associates itself with the “json”, “application/json”, “application/x-javascript”, “text/javascript”, “text/x-javascript”, and “text/x-json” MIME types.
- build_tree(path: str, options: Optional[graphtage.BuildOptions] = None) graphtage.TreeNode¶
Builds an intermediate representation tree from a file of this
Filetype.- Parameters
path – Path to the file to parse
options – An optional set of options for building the tree
- Returns
The root tree node of the provided file
- Return type
- build_tree_handling_errors(path: str, options: Optional[graphtage.BuildOptions] = None) Union[str, graphtage.TreeNode]¶
Same as
Filetype.build_tree(), but it should return a human-readable error string on failure.This function should never throw an exception.
- get_default_formatter() graphtage.json.JSONFormatter¶
Returns the default formatter for printing files of this type.
JSON5¶
- class graphtage.json.JSON5¶
Bases:
graphtage.FiletypeThe JSON5 file type.
- __init__()¶
Initializes the JSON5 file type.
By default, JSON5 associates itself with the “json5”, “application/json5”, and “text/x-json5” MIME types.
- build_tree(path: str, options: Optional[graphtage.BuildOptions] = None) graphtage.TreeNode¶
Builds an intermediate representation tree from a file of this
Filetype.- Parameters
path – Path to the file to parse
options – An optional set of options for building the tree
- Returns
The root tree node of the provided file
- Return type
- build_tree_handling_errors(path: str, options: Optional[graphtage.BuildOptions] = None) Union[str, graphtage.TreeNode]¶
Same as
Filetype.build_tree(), but it should return a human-readable error string on failure.This function should never throw an exception.
- get_default_formatter() graphtage.json.JSONFormatter¶
Returns the default formatter for printing files of this type.
JSONDictFormatter¶
- class graphtage.json.JSONDictFormatter(*args, **kwargs)¶
Bases:
graphtage.sequences.SequenceFormatterA sub-formatter for JSON dicts.
- DEFAULT_INSTANCE: Formatter[T] = <graphtage.json.JSONDictFormatter object>¶
A default instance of this formatter, automatically instantiated by the
FormatterCheckermetaclass.
- __init__()¶
Initializes a sequence formatter.
- Parameters
start_symbol – The symbol to print at the start of the sequence.
end_symbol – The symbol to print at the end of the sequence.
delimiter – A delimiter to print between items.
delimiter_callback –
A callback for when a delimiter is to be printed. If omitted, this defaults to:
lambda p: p.write(delimiter)
- static __new__(cls, *args, **kwargs) graphtage.formatter.Formatter[graphtage.formatter.T]¶
Instantiates a new formatter.
This automatically instantiates and populates
Formatter.sub_formattersand sets theirparentto this new formatter.
- edit_print(printer: graphtage.printer.Printer, edit: graphtage.Edit)¶
Called when the edit for an item is to be printed.
If the
SequenceNodebeing printed either is not edited or has no edits, then the edit passed to this function will be aMatch(child, child, 0).This implementation simply delegates the print to the Formatting Protocol:
self.print(printer, edit)
- get_formatter(item: graphtage.formatter.T) Optional[Callable[[graphtage.printer.Printer, graphtage.formatter.T], Any]]¶
Looks up a formatter for the given item using this formatter as a base.
Equivalent to:
get_formatter(item.__class__, base_formatter=self)
- is_partial: bool = True¶
This is a partial formatter; it will not be automatically used in the Formatting Protocol.
- item_newline(printer: graphtage.printer.Printer, is_first: bool = False, is_last: bool = False)¶
Called before each node is printed.
This is also called one extra time after the last node, if there is at least one node printed.
The default implementation is simply:
printer.newline()
- items_indent(printer: graphtage.printer.Printer) graphtage.printer.Printer¶
Returns a Printer context with an indentation.
This is called as:
with self.items_indent(printer) as p:
immediately after the
self.start_symbolis printed, but before any of the items have been printed.This default implementation is equivalent to:
return printer.indent()
- parent: Optional[Formatter[T]] = None¶
The parent formatter for this formatter instance.
This is automatically populated by
Formatter.__new__()and should never be manually modified.
- print(printer: graphtage.printer.Printer, node_or_edit: Union[graphtage.TreeNode, graphtage.Edit], with_edits: bool = True)¶
Prints the given node or edit.
- Parameters
printer – The printer to which to write.
node_or_edit – The node or edit to print.
with_edits – If :keyword:True, print any edits associated with the node.
Note
The protocol for determining how a node or edit should be printed is very complex due to its extensibility. See the Printing Protocol for a detailed description.
- print_MappingNode(*args, **kwargs)¶
Prints a
graphtage.MappingNode.Equivalent to:
super().print_SequenceNode(*args, **kwargs)
- print_MultiSetNode(*args, **kwargs)¶
Prints a
graphtage.MultiSetNode.Equivalent to:
super().print_SequenceNode(*args, **kwargs)
- print_SequenceNode(*args, **kwargs)¶
Prints a non-Dict sequence.
This delegates to the parent formatter’s implementation:
self.parent.print(*args, **kwargs)
which should invoke
JSONFormatter.print(), thereby delegating to theJSONListFormatterin instances where a dict contains a list.
- property root: graphtage.formatter.Formatter[graphtage.formatter.T]¶
Returns the root formatter.
- sub_format_types: Sequence[Type[Formatter[T]]] = ()¶
A list of formatter types that should be used as sub-formatters in the Formatting Protocol.
JSONFormatter¶
- class graphtage.json.JSONFormatter(*args, **kwargs)¶
Bases:
graphtage.GraphtageFormatterThe default JSON formatter.
- DEFAULT_INSTANCE: Formatter[T] = <graphtage.json.JSONFormatter object>¶
A default instance of this formatter, automatically instantiated by the
FormatterCheckermetaclass.
- __init__()¶
- static __new__(cls, *args, **kwargs) graphtage.formatter.Formatter[graphtage.formatter.T]¶
Instantiates a new formatter.
This automatically instantiates and populates
Formatter.sub_formattersand sets theirparentto this new formatter.
- get_formatter(item: graphtage.formatter.T) Optional[Callable[[graphtage.printer.Printer, graphtage.formatter.T], Any]]¶
Looks up a formatter for the given item using this formatter as a base.
Equivalent to:
get_formatter(item.__class__, base_formatter=self)
- parent: Optional[Formatter[T]] = None¶
The parent formatter for this formatter instance.
This is automatically populated by
Formatter.__new__()and should never be manually modified.
- print(printer: graphtage.printer.Printer, node_or_edit: Union[graphtage.TreeNode, graphtage.Edit], with_edits: bool = True)¶
Prints the given node or edit.
- Parameters
printer – The printer to which to write.
node_or_edit – The node or edit to print.
with_edits – If :keyword:True, print any edits associated with the node.
Note
The protocol for determining how a node or edit should be printed is very complex due to its extensibility. See the Printing Protocol for a detailed description.
- print_ContainerNode(printer: graphtage.printer.Printer, node: graphtage.ContainerNode)¶
Prints a
graphtage.ContainerNode.This is a fallback to permit the printing of custom containers, like
graphtage.xml.XMLElement.
- print_KeyValuePairNode(printer: graphtage.printer.Printer, node: graphtage.KeyValuePairNode)¶
Prints a
graphtage.KeyValuePairNode.By default, the key is printed in blue, followed by a bright “: “, followed by the value.
- print_LeafNode(printer: graphtage.printer.Printer, node: graphtage.LeafNode)¶
Prints a
graphtage.LeafNode.This is equivalent to:
printer.write(json.dumps(node.object))
- print_XMLElement(printer: graphtage.printer.Printer, node: graphtage.xml.XMLElement)¶
- property root: graphtage.formatter.Formatter[graphtage.formatter.T]¶
Returns the root formatter.
- sub_format_types: Sequence[Type[Formatter[T]]] = [<class 'graphtage.json.JSONStringFormatter'>, <class 'graphtage.json.JSONListFormatter'>, <class 'graphtage.json.JSONDictFormatter'>]¶
A list of formatter types that should be used as sub-formatters in the Formatting Protocol.
JSONListFormatter¶
- class graphtage.json.JSONListFormatter(*args, **kwargs)¶
Bases:
graphtage.sequences.SequenceFormatterA sub-formatter for JSON lists.
- DEFAULT_INSTANCE: Formatter[T] = <graphtage.json.JSONListFormatter object>¶
A default instance of this formatter, automatically instantiated by the
FormatterCheckermetaclass.
- __init__()¶
Initializes the JSON list formatter.
Equivalent to:
super().__init__('[', ']', ',')
- static __new__(cls, *args, **kwargs) graphtage.formatter.Formatter[graphtage.formatter.T]¶
Instantiates a new formatter.
This automatically instantiates and populates
Formatter.sub_formattersand sets theirparentto this new formatter.
- edit_print(printer: graphtage.printer.Printer, edit: graphtage.Edit)¶
Called when the edit for an item is to be printed.
If the
SequenceNodebeing printed either is not edited or has no edits, then the edit passed to this function will be aMatch(child, child, 0).This implementation simply delegates the print to the Formatting Protocol:
self.print(printer, edit)
- get_formatter(item: graphtage.formatter.T) Optional[Callable[[graphtage.printer.Printer, graphtage.formatter.T], Any]]¶
Looks up a formatter for the given item using this formatter as a base.
Equivalent to:
get_formatter(item.__class__, base_formatter=self)
- is_partial: bool = True¶
This is a partial formatter; it will not be automatically used in the Formatting Protocol.
- item_newline(printer: graphtage.printer.Printer, is_first: bool = False, is_last: bool = False)¶
Called before each node is printed.
This is also called one extra time after the last node, if there is at least one node printed.
The default implementation is simply:
printer.newline()
- items_indent(printer: graphtage.printer.Printer) graphtage.printer.Printer¶
Returns a Printer context with an indentation.
This is called as:
with self.items_indent(printer) as p:
immediately after the
self.start_symbolis printed, but before any of the items have been printed.This default implementation is equivalent to:
return printer.indent()
- parent: Optional[Formatter[T]] = None¶
The parent formatter for this formatter instance.
This is automatically populated by
Formatter.__new__()and should never be manually modified.
- print(printer: graphtage.printer.Printer, node_or_edit: Union[graphtage.TreeNode, graphtage.Edit], with_edits: bool = True)¶
Prints the given node or edit.
- Parameters
printer – The printer to which to write.
node_or_edit – The node or edit to print.
with_edits – If :keyword:True, print any edits associated with the node.
Note
The protocol for determining how a node or edit should be printed is very complex due to its extensibility. See the Printing Protocol for a detailed description.
- print_ListNode(*args, **kwargs)¶
Prints a
graphtage.ListNode.Equivalent to:
super().print_SequenceNode(*args, **kwargs)
- print_SequenceNode(*args, **kwargs)¶
Prints a non-List sequence.
This delegates to the parent formatter’s implementation:
self.parent.print(*args, **kwargs)
which should invoke
JSONFormatter.print(), thereby delegating to theJSONDictFormatterin instances where a list contains a dict.
- property root: graphtage.formatter.Formatter[graphtage.formatter.T]¶
Returns the root formatter.
- sub_format_types: Sequence[Type[Formatter[T]]] = ()¶
A list of formatter types that should be used as sub-formatters in the Formatting Protocol.
JSONStringFormatter¶
- class graphtage.json.JSONStringFormatter(*args, **kwargs)¶
Bases:
graphtage.StringFormatterA JSON formatter for strings.
- DEFAULT_INSTANCE: Formatter[T] = <graphtage.json.JSONStringFormatter object>¶
A default instance of this formatter, automatically instantiated by the
FormatterCheckermetaclass.
- __init__()¶
- static __new__(cls, *args, **kwargs) graphtage.formatter.Formatter[graphtage.formatter.T]¶
Instantiates a new formatter.
This automatically instantiates and populates
Formatter.sub_formattersand sets theirparentto this new formatter.
- context(printer: graphtage.printer.Printer)¶
- escape(c: str) str¶
String escape.
This function is called once for each character in the string.
- Returns
The escaped version of c, or c itself if no escaping is required.
- Return type
This is equivalent to:
printer.write(json.dumps(c)[1:-1])
- get_formatter(item: graphtage.formatter.T) Optional[Callable[[graphtage.printer.Printer, graphtage.formatter.T], Any]]¶
Looks up a formatter for the given item using this formatter as a base.
Equivalent to:
get_formatter(item.__class__, base_formatter=self)
- parent: Optional['Formatter[T]'] = None¶
The parent formatter for this formatter instance.
This is automatically populated by
Formatter.__new__()and should never be manually modified.
- print(printer: graphtage.printer.Printer, node_or_edit: Union[graphtage.TreeNode, graphtage.Edit], with_edits: bool = True)¶
Prints the given node or edit.
- Parameters
printer – The printer to which to write.
node_or_edit – The node or edit to print.
with_edits – If :keyword:True, print any edits associated with the node.
Note
The protocol for determining how a node or edit should be printed is very complex due to its extensibility. See the Printing Protocol for a detailed description.
- print_StringEdit(printer: graphtage.printer.Printer, edit: graphtage.StringEdit)¶
- print_StringNode(printer: graphtage.printer.Printer, node: graphtage.StringNode)¶
- property root: graphtage.formatter.Formatter[graphtage.formatter.T]¶
Returns the root formatter.
- sub_format_types: Sequence[Type['Formatter[T]']] = ()¶
A list of formatter types that should be used as sub-formatters in the Formatting Protocol.
- sub_formatters: List['Formatter[T]'] = []¶
The list of instantiated formatters corresponding to
Formatter.sub_format_types.This list is automatically populated by
Formatter.__new__()and should never be manually modified.
- write_char(printer: graphtage.printer.Printer, c: str, index: int, num_edits: int, removed=False, inserted=False)¶
Writes a character to the printer.
Note
This function calls
graphtage.StringFormatter.escape(); classes extendinggraphtage.StringFormattershould also callgraphtage.StringFormatter.escape()when reimplementing this function.Note
There is no need to specially format characters that have been removed or inserted; the printer will have already automatically been configured to format them prior to the call to
StringFormatter.write_char().- Parameters
printer – The printer to which to write the character.
c – The character to write.
index – The index of the character in the string.
num_edits – The total number of characters that will be printed.
removed – Whether this character was removed from the source string.
inserted – Whether this character is inserted into the source string.
- write_end_quote(printer: graphtage.printer.Printer, _)¶
Prints an ending quote for the string
- write_start_quote(printer: graphtage.printer.Printer, _)¶
Prints a starting quote for the string
json functions¶
build_tree¶
- graphtage.json.build_tree(python_obj: Union[int, float, bool, str, bytes, list, dict], options: Optional[graphtage.BuildOptions] = None, force_leaf_node: bool = False) graphtage.TreeNode¶
Builds a Graphtage tree from an arbitrary Python object.
- Parameters
python_obj – The object from which to build the tree.
options – An optional set of options for building the tree.
force_leaf_node – If
True, assume thatpython_objis not alist()ordict().
- Returns
The resulting tree.
- Return type
- Raises
ValueError – If
force_leaf_nodeisTrueandpython_objis not one ofint,float,bool,str, orbytes.ValueError – If the object is of an unsupported type.