defdeserialize(data:str,fmt:SerializeFormatStr,**kwargs:Any)->Any:"""Serialize given json-like object to given format. Args: data: The data to deserialize fmt: The serialization format kwargs: Keyword arguments passed to the loader function """matchfmt:case"yaml":importyamlingreturnyamling.load_yaml(data,**kwargs)case"json":returnjson.loads(data,**kwargs)case"ini":returnload_ini(data,**kwargs)case"toml":importtomllibreturntomllib.loads(data,**kwargs)case_:raiseTypeError(fmt)
defdo_dictsort(value:t.Mapping[K,V],case_sensitive:bool=False,by:'te.Literal["key", "value"]'="key",reverse:bool=False,)->t.List[t.Tuple[K,V]]:"""Sort a dict and yield (key, value) pairs. Python dicts may not be in the order you want to display them in, so sort them first. .. sourcecode:: jinja {% for key, value in mydict|dictsort %} sort the dict by key, case insensitive {% for key, value in mydict|dictsort(reverse=true) %} sort the dict by key, case insensitive, reverse order {% for key, value in mydict|dictsort(true) %} sort the dict by key, case sensitive {% for key, value in mydict|dictsort(false, 'value') %} sort the dict by value, case insensitive """ifby=="key":pos=0elifby=="value":pos=1else:raiseFilterArgumentError('You can only sort by either "key" or "value"')defsort_func(item:t.Tuple[t.Any,t.Any])->t.Any:value=item[pos]ifnotcase_sensitive:value=ignore_case(value)returnvaluereturnsorted(value.items(),key=sort_func,reverse=reverse)
defdig(data:dict,*sections:str,keep_path:bool=False,dig_yaml_lists:bool=True,)->Any:"""Try to get data with given section path from a dict-list structure. If a list is encountered and dig_yaml_lists is true, treat it like a list of {"identifier", {subdict}} items, as used in MkDocs config for plugins & extensions. If Key path does not exist, return None. Args: data: The data to dig into sections: Sections to dig into keep_path: Return result with original nesting dig_yaml_lists: Also dig into single-key->value pairs, as often found in yaml. """foriinsections:ifisinstance(data,dict):ifchild:=data.get(i):data=childelse:returnNoneelifdig_yaml_listsandisinstance(data,list):# this part is for yaml-style listitemsforidxindata:ifiinidxandisinstance(idx,dict):data=idx[i]breakifisinstance(idx,str)andidx==i:data=idxbreakelse:returnNoneifnotkeep_path:returndataresult:dict[str,dict]={}new=resultforsectinsections:result[sect]=dataifsect==sections[-1]else{}result=result[sect]returnnew
defdumps(obj,*,skipkeys=False,ensure_ascii=True,check_circular=True,allow_nan=True,cls=None,indent=None,separators=None,default=None,sort_keys=False,**kw):"""Serialize ``obj`` to a JSON formatted ``str``. If ``skipkeys`` is true then ``dict`` keys that are not basic types (``str``, ``int``, ``float``, ``bool``, ``None``) will be skipped instead of raising a ``TypeError``. If ``ensure_ascii`` is false, then the return value can contain non-ASCII characters if they appear in strings contained in ``obj``. Otherwise, all such characters are escaped in JSON strings. If ``check_circular`` is false, then the circular reference check for container types will be skipped and a circular reference will result in an ``RecursionError`` (or worse). If ``allow_nan`` is false, then it will be a ``ValueError`` to serialize out of range ``float`` values (``nan``, ``inf``, ``-inf``) in strict compliance of the JSON specification, instead of using the JavaScript equivalents (``NaN``, ``Infinity``, ``-Infinity``). 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. ``default(obj)`` is a function that should return a serializable version of obj or raise TypeError. The default simply raises TypeError. If *sort_keys* is true (default: ``False``), then the output of dictionaries will be sorted by key. To use a custom ``JSONEncoder`` subclass (e.g. one that overrides the ``.default()`` method to serialize additional types), specify it with the ``cls`` kwarg; otherwise ``JSONEncoder`` is used. """# cached encoderif(notskipkeysandensure_asciiandcheck_circularandallow_nanandclsisNoneandindentisNoneandseparatorsisNoneanddefaultisNoneandnotsort_keysandnotkw):return_default_encoder.encode(obj)ifclsisNone:cls=JSONEncoderreturncls(skipkeys=skipkeys,ensure_ascii=ensure_ascii,check_circular=check_circular,allow_nan=allow_nan,indent=indent,separators=separators,default=default,sort_keys=sort_keys,**kw).encode(obj)
defdo_items(value:t.Union[t.Mapping[K,V],Undefined])->t.Iterator[t.Tuple[K,V]]:"""Return an iterator over the ``(key, value)`` items of a mapping. ``x|items`` is the same as ``x.items()``, except if ``x`` is undefined an empty iterator is returned. This filter is useful if you expect the template to be rendered with an implementation of Jinja in another programming language that does not have a ``.items()`` method on its mapping type. .. code-block:: html+jinja <dl> {% for key, value in my_dict|items %} <dt>{{ key }} <dd>{{ value }} {% endfor %} </dl> .. versionadded:: 3.1 """ifisinstance(value,Undefined):returnifnotisinstance(value,abc.Mapping):raiseTypeError("Can only get item pairs from a mapping.")yield fromvalue.items()
defloads(s,*,cls=None,object_hook=None,parse_float=None,parse_int=None,parse_constant=None,object_pairs_hook=None,**kw):"""Deserialize ``s`` (a ``str``, ``bytes`` or ``bytearray`` instance containing a JSON document) to a Python object. ``object_hook`` is an optional function that will be called with the result of any object literal decode (a ``dict``). The return value of ``object_hook`` will be used instead of the ``dict``. This feature can be used to implement custom decoders (e.g. JSON-RPC class hinting). ``object_pairs_hook`` is an optional function that will be called with the result of any object literal decoded with an ordered list of pairs. The return value of ``object_pairs_hook`` will be used instead of the ``dict``. This feature can be used to implement custom decoders. If ``object_hook`` is also defined, the ``object_pairs_hook`` takes priority. ``parse_float``, if specified, will be called with the string of every JSON float to be decoded. By default this is equivalent to float(num_str). This can be used to use another datatype or parser for JSON floats (e.g. decimal.Decimal). ``parse_int``, if specified, will be called with the string of every JSON int to be decoded. By default this is equivalent to int(num_str). This can be used to use another datatype or parser for JSON integers (e.g. float). ``parse_constant``, if specified, will be called with one of the following strings: -Infinity, Infinity, NaN. This can be used to raise an exception if invalid JSON numbers are encountered. To use a custom ``JSONDecoder`` subclass, specify it with the ``cls`` kwarg; otherwise ``JSONDecoder`` is used. """ifisinstance(s,str):ifs.startswith('\ufeff'):raiseJSONDecodeError("Unexpected UTF-8 BOM (decode using utf-8-sig)",s,0)else:ifnotisinstance(s,(bytes,bytearray)):raiseTypeError(f'the JSON object must be str, bytes or bytearray, 'f'not {s.__class__.__name__}')s=s.decode(detect_encoding(s),'surrogatepass')if(clsisNoneandobject_hookisNoneandparse_intisNoneandparse_floatisNoneandparse_constantisNoneandobject_pairs_hookisNoneandnotkw):return_default_decoder.decode(s)ifclsisNone:cls=JSONDecoderifobject_hookisnotNone:kw['object_hook']=object_hookifobject_pairs_hookisnotNone:kw['object_pairs_hook']=object_pairs_hookifparse_floatisnotNone:kw['parse_float']=parse_floatifparse_intisnotNone:kw['parse_int']=parse_intifparse_constantisnotNone:kw['parse_constant']=parse_constantreturncls(**kw).decode(s)
defloads(s:str,/,*,parse_float:ParseFloat=float)->dict[str,Any]:# noqa: C901"""Parse TOML from a string."""# The spec allows converting "\r\n" to "\n", even in string# literals. Let's do so to simplify parsing.src=s.replace("\r\n","\n")pos=0out=Output(NestedDict(),Flags())header:Key=()parse_float=make_safe_parse_float(parse_float)# Parse one statement at a time# (typically means one line in TOML source)whileTrue:# 1. Skip line leading whitespacepos=skip_chars(src,pos,TOML_WS)# 2. Parse rules. Expect one of the following:# - end of file# - end of line# - comment# - key/value pair# - append dict to list (and move to its namespace)# - create dict (and move to its namespace)# Skip trailing whitespace when applicable.try:char=src[pos]exceptIndexError:breakifchar=="\n":pos+=1continueifcharinKEY_INITIAL_CHARS:pos=key_value_rule(src,pos,out,header,parse_float)pos=skip_chars(src,pos,TOML_WS)elifchar=="[":try:second_char:str|None=src[pos+1]exceptIndexError:second_char=Noneout.flags.finalize_pending()ifsecond_char=="[":pos,header=create_list_rule(src,pos,out)else:pos,header=create_dict_rule(src,pos,out)pos=skip_chars(src,pos,TOML_WS)elifchar!="#":raisesuffixed_err(src,pos,"Invalid statement")# 3. Skip commentpos=skip_comment(src,pos)# 4. Expect end of line or end of filetry:char=src[pos]exceptIndexError:breakifchar!="\n":raisesuffixed_err(src,pos,"Expected newline or end of document after a statement")pos+=1returnout.data.dict
defmerge(target:list|dict,*source:list|dict,deepcopy:bool=False,mergers:dict[type,Callable[[Any,Any,Any],Any]]|None=None,)->list|dict:"""Merge given data structures using mergers provided. Args: target: Data structure to merge into source: Data structures to merge into target deepcopy: Whether to deepcopy the target mergers: Mergers with strategies for each type (default: additive) """importcopyifdeepcopy:target=copy.deepcopy(target)context=deepmerge.DeepMerger(mergers)forsinsource:target=context.merge(s,target)returntarget
defserialize(data:Any,fmt:SerializeFormatStr,**kwargs:Any)->str:"""Serialize given json-like object to given format. Args: data: The data to serialize fmt: The serialization format kwargs: Keyword arguments passed to the dumper function """matchfmt:case"yaml":importyamlingreturnyamling.dump_yaml(data,**kwargs)case"json":returnjson.dumps(data,indent=4,**kwargs)case"ini":config=configparser.ConfigParser(**kwargs)config.read_dict(data)file=io.StringIO()withfileasfp:config.write(fp)returnfile.getvalue()case"toml"ifisinstance(data,dict):importtomli_wreturntomli_w.dumps(data,**kwargs)case_:raiseTypeError(fmt)
@pass_eval_contextdefdo_tojson(eval_ctx:"EvalContext",value:t.Any,indent:t.Optional[int]=None)->Markup:"""Serialize an object to a string of JSON, and mark it safe to render in HTML. This filter is only for use in HTML documents. The returned string is safe to render in HTML documents and ``<script>`` tags. The exception is in HTML attributes that are double quoted; either use single quotes or the ``|forceescape`` filter. :param value: The object to serialize to JSON. :param indent: The ``indent`` parameter passed to ``dumps``, for pretty-printing the value. .. versionadded:: 2.9 """policies=eval_ctx.environment.policiesdumps=policies["json.dumps_function"]kwargs=policies["json.dumps_kwargs"]ifindentisnotNone:kwargs=kwargs.copy()kwargs["indent"]=indentreturnhtmlsafe_json_dumps(value,dumps=dumps,**kwargs)