Module scute.internal.dict_to_NBT
Expand source code Browse git
import json
from scute.data_types import _NumberType
def encode_value(value):
out = ""
# If the value is a NBT number like 1b, get its NBT representation
if issubclass(type(value), _NumberType):
out += value.getNbt()
# If the value is a dict or list, encode it
elif isinstance(value, dict) or isinstance(value, list):
out += encode_dict_or_list(value)
# If the value is a string, just add it
elif isinstance(value, str):
escapedValue = value.replace("'", "\\'")
out += f"'{escapedValue}'"
# If the value is an int, just add it
elif isinstance(value, int) or isinstance(value, float):
out += str(value)
return out
def encode_dict_or_list(obj):
out = ""
index = 0
if isinstance(obj, dict):
out = "{"
# Loop through keys and values of the dict
for key, value in obj.items():
if index != 0:
out += ", "
# Add the key and value to the output
out += str(key) + ": "
out += encode_value(value)
index += 1
out += "}"
elif isinstance(obj, list):
out += "["
for value in obj:
if index != 0:
out += ", "
out += encode_value(value)
out += "]"
return out
class dtn(json.JSONEncoder):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def encode(self, obj):
return encode_dict_or_list(obj)
def dict_to_NBT(dic):
return json.dumps(dic, cls=dtn)
Functions
def dict_to_NBT(dic)
-
Expand source code Browse git
def dict_to_NBT(dic): return json.dumps(dic, cls=dtn)
def encode_dict_or_list(obj)
-
Expand source code Browse git
def encode_dict_or_list(obj): out = "" index = 0 if isinstance(obj, dict): out = "{" # Loop through keys and values of the dict for key, value in obj.items(): if index != 0: out += ", " # Add the key and value to the output out += str(key) + ": " out += encode_value(value) index += 1 out += "}" elif isinstance(obj, list): out += "[" for value in obj: if index != 0: out += ", " out += encode_value(value) out += "]" return out
def encode_value(value)
-
Expand source code Browse git
def encode_value(value): out = "" # If the value is a NBT number like 1b, get its NBT representation if issubclass(type(value), _NumberType): out += value.getNbt() # If the value is a dict or list, encode it elif isinstance(value, dict) or isinstance(value, list): out += encode_dict_or_list(value) # If the value is a string, just add it elif isinstance(value, str): escapedValue = value.replace("'", "\\'") out += f"'{escapedValue}'" # If the value is an int, just add it elif isinstance(value, int) or isinstance(value, float): out += str(value) return out
Classes
class dtn (*args, **kwargs)
-
Extensible JSON https://json.org encoder for Python data structures.
Supports the following objects and types by default:
+-------------------+---------------+ | Python | JSON | +===================+===============+ | dict | object | +-------------------+---------------+ | list, tuple | array | +-------------------+---------------+ | str | string | +-------------------+---------------+ | int, float | number | +-------------------+---------------+ | True | true | +-------------------+---------------+ | False | false | +-------------------+---------------+ | None | null | +-------------------+---------------+
To extend this to recognize other objects, subclass and implement a
.default()
method with another method that returns a serializable object foro
if possible, otherwise it should call the superclass implementation (to raiseTypeError
).Constructor for JSONEncoder, with sensible defaults.
If skipkeys is false, then it is a TypeError to attempt encoding of keys that are not str, int, float or None. If skipkeys is True, such items are simply skipped.
If ensure_ascii is true, the output is guaranteed to be str objects with all incoming non-ASCII characters escaped. If ensure_ascii is false, the output can contain non-ASCII characters.
If check_circular is true, then lists, dicts, and custom encoded objects will be checked for circular references during encoding to prevent an infinite recursion (which would cause an RecursionError). Otherwise, no such check takes place.
If allow_nan is true, then NaN, Infinity, and -Infinity will be encoded as such. This behavior is not JSON specification compliant, but is consistent with most JavaScript based encoders and decoders. Otherwise, it will be a ValueError to encode such floats.
If sort_keys is true, then the output of dictionaries will be sorted by key; this is useful for regression tests to ensure that JSON serializations can be compared on a day-to-day basis.
If indent is a non-negative integer, then JSON array elements and object members will be pretty-printed with that indent level. An indent level of 0 will only insert newlines. None is the most compact representation.
If specified, separators should be an (item_separator, key_separator) tuple. The default is (', ', ': ') if indent is
None
and (',', ': ') otherwise. To get the most compact JSON representation, you should specify (',', ':') to eliminate whitespace.If specified, default is a function that gets called for objects that can't otherwise be serialized. It should return a JSON encodable version of the object or raise a
TypeError
.Expand source code Browse git
class dtn(json.JSONEncoder): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) def encode(self, obj): return encode_dict_or_list(obj)
Ancestors
- json.encoder.JSONEncoder
Methods
def encode(self, obj)
-
Return a JSON string representation of a Python data structure.
>>> from json.encoder import JSONEncoder >>> JSONEncoder().encode({"foo": ["bar", "baz"]}) '{"foo": ["bar", "baz"]}'
Expand source code Browse git
def encode(self, obj): return encode_dict_or_list(obj)