import json
json.dumps(python数据对象)
json.dumps(obj, fp[, skipkeys[, ensure_ascii[, check_circular[, allow_nan[, cls[, indent[, separators[, encoding[, default[, **kw]]]]]]]]]])¶
Serialize obj as a JSON formatted stream to fp (a .write()-supportingfile-like object).
If skipkeys is True (default: False), then dict keys that are not of a basic type (str, unicode, int, long,float, bool, None) will be skipped instead of raising aTypeError. 可以不要设置简单key的。
json.loads(s[, encoding[, cls[, object_hook[, parse_float[, parse_int[, parse_constant[, object_pairs_hook[, **kw]]]]]]]])
反向操作。
>>> x = {1:'234234', 2:'sdf', 3:'sdf', 4:'asdf'}
>>> x
{1: '234234', 2: 'sdf', 3: 'sdf', 4: 'asdf'}
>>> y = json.dumps(x)
>>> z=json.loads(y)
{u'1': u'234234', u'3': u'sdf', u'2': u'sdf', u'4': u'asdf'} 注意数字的key转换成字符了。json默认都是string类型的。dump(x, f)可以直接写到文件中。
直接dumps数据库对象数据表什么的
from django.core import serializers
json.dumps(serializers.serialize("json", models.objects.all()))