1. 程式人生 > >dict to json And json to dict

dict to json And json to dict

json.dump(objfpskipkeys=Falseensure_ascii=Truecheck_circular=Trueallow_nan=Truecls=Noneindent=Noneseparators=Noneencoding="utf-8"default=Nonesort_keys=False**kw)

Serialize obj as a JSON formatted stream to fp (a .write()-supporting file-like object) using this conversion table

.

If skipkeys is true (default: False), then dict keys that are not of a basic type (strunicodeintlongfloatboolNone) will be skipped instead of raising a TypeError.

If ensure_ascii is true (the default), all non-ASCII characters in the output are escaped with \uXXXX sequences, and the result is a 

str instance consisting of ASCII characters only. If ensure_ascii is false, some chunks written to fp may be unicode instances. This usually happens because the input contains unicode strings or the encoding parameter is used. Unless fp.write() explicitly understands unicode (as in codecs.getwriter()
) this is likely to cause an error.

If check_circular is false (default: True), then the circular reference check for container types will be skipped and a circular reference will result in an OverflowError (or worse).

If allow_nan is false (default: True), then it will be a ValueError to serialize out of range float values (naninf-inf) in strict compliance of the JSON specification. If allow_nan is true, their JavaScript equivalents (NaNInfinity-Infinity) will be used.

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, or negative, will only insert newlines. None (the default) selects the most compact representation.

Note

 

Since the default item separator is ', ', the output might include trailing whitespace when indent is specified. You can use separators=(',', ': ') to avoid this.

If specified, separators should be an (item_separator, key_separator) tuple. By default, (', ', ': ') are used. To get the most compact JSON representation, you should specify (',', ':') to eliminate whitespace.

encoding is the character encoding for str instances, default is UTF-8.

If specified, default should be 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. If not specified, TypeError is raised.

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.

Note

 

Unlike pickle and marshal, JSON is not a framed protocol so trying to serialize more objects with repeated calls to dump() and the same fp will result in an invalid JSON file.

json.dumps(objskipkeys=Falseensure_ascii=Truecheck_circular=Trueallow_nan=Truecls=Noneindent=Noneseparators=Noneencoding="utf-8"default=Nonesort_keys=False**kw)

Serialize obj to a JSON formatted str using this conversion table. If ensure_ascii is false, the result may contain non-ASCII characters and the return value may be a unicode instance.

The arguments have the same meaning as in dump().

Note

 

Keys in key/value pairs of JSON are always of the type str. When a dictionary is converted into JSON, all the keys of the dictionary are coerced to strings. As a result of this, if a dictionary is converted into JSON and then back into a dictionary, the dictionary may not equal the original one. That is, loads(dumps(x)) != x if x has non-string keys.

json.load(fp[encoding[cls[object_hook[parse_float[parse_int[parse_constant[object_pairs_hook[**kw]]]]]]]])

Deserialize fp (a .read()-supporting file-like object containing a JSON document) to a Python object using this conversion table.

If the contents of fp are encoded with an ASCII based encoding other than UTF-8 (e.g. latin-1), then an appropriate encoding name must be specified. Encodings that are not ASCII based (such as UCS-2) are not allowed, and should be wrapped with codecs.getreader(encoding)(fp), or simply decoded to a unicode object and passed to loads().

object_hook is an optional function that will be called with the result of any object literal decoded (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 that rely on the order that the key and value pairs are decoded (for example, collections.OrderedDict() will remember the order of insertion). If object_hook is also defined, the object_pairs_hook takes priority.

Changed in version 2.7: Added support for object_pairs_hook.

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.

Changed in version 2.7: parse_constant doesn’t get called on ‘null’, ‘true’, ‘false’ anymore.

To use a custom JSONDecoder subclass, specify it with the cls kwarg; otherwise JSONDecoder is used. Additional keyword arguments will be passed to the constructor of the class.

json.loads(s[encoding[cls[object_hook[parse_float[parse_int[parse_constant[object_pairs_hook[**kw]]]]]]]])

Deserialize s (a str or unicode instance containing a JSON document) to a Python object using this conversion table.

If s is a str instance and is encoded with an ASCII based encoding other than UTF-8 (e.g. latin-1), then an appropriate encoding name must be specified. Encodings that are not ASCII based (such as UCS-2) are not allowed and should be decoded to unicode first.

The other arguments have the same meaning as in load().