Python读写json格式文件

转自:http://blog.csdn.net/zhanh1218/article/details/26009329?utm_source=tuicool&utm_medium=referral
JSON-是一个轻量级的数据交换格式。意味着可以被N多语言读取;可以存在本地,避免数据多次处理; 还可以通过socket和网络上其他计算机交换数据。

一、dump

 dump (obj, fp, skipkeys=False, ensure_ascii=True, 
 check_circular=True, allow_nan=True, cls=None, indent=None, 
 separators=None, encoding='utf-8', default=None, sort_keys=False, **kw)

解释:

Serialize obj as a JSON formatted stream to fp (a .write()-supporting file-like object).
即:序列化obj为JSON格式的流写入fp(file-like object)。

If skipkeys is true then dict keys that are not basic types (str, unicode, int, long, float, bool, None) will be skipped instead of raising a TypeError.
即: skipkeys为真时,dict的keys不是基础类型(str, unicode, int, long, float, bool, None)的一种则不会抛出TypeError`异常,而是被忽略!

>>> a = {"中国": 1, "china": 11, "北京天安门": 111, ("tuple",): 1111}
>>> json.dumps(a)

Traceback (most recent call last):
  File "<pyshell#67>", line 1, in <module>
    json.dumps(a)
  File "C:\Python27\lib\json\__init__.py", line 243, in dumps
    return _default_encoder.encode(obj)
  File "C:\Python27\lib\json\encoder.py", line 207, in encode
    chunks = self.iterencode(o, _one_shot=True)
  File "C:\Python27\lib\json\encoder.py", line 270, in iterencode
    return _iterencode(o, 0)
TypeError: keys must be a string
>>> print json.dumps(a, skipkeys = True, ensure_ascii = False, encoding = "gb2312")
{"北京天安门": 111, "中国": 1, "china": 11}
>>>

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. Since the default item separator is ', ', the output might include trailing whitespace when indent is specified. You can use separators=(',', ': ') to avoid this.
indent:格式化输出!默认None为最紧凑的格式。只能为非负整数,设置为0的时候为换行!和separators结合起来使用!

If separators is an (item_separator, dict_separator) tuple then it will be used instead of the default (', ', ': ') separators. (',', ':') is the most compact JSON representation.

>> a = {"中国": 1, "china": 11, "北京天安门": 111}
>>> print json.dumps(a, ensure_ascii = False, encoding = "gb2312", indent = None)
{"北京天安门": 111, "中国": 1, "china": 11}
>>> print json.dumps(a, ensure_ascii = False, encoding = "gb2312", indent = 0)
{
"北京天安门": 111, 
"中国": 1, 
"china": 11
}
>>> print json.dumps(a, ensure_ascii = False, encoding = "gb2312", indent = 4)
{
  "北京天安门": 111, 
  "中国": 1, 
  "china": 11
}
>>> print json.dumps(a, ensure_ascii = False, encoding = "gb2312", indent = 4, separators = (',',':'))
{
  "北京天安门":111,
  "中国":1,
  "china":11
}
>>

二、dumps

dumps (obj, skipkeys=False, ensure_ascii=True, check_circular=True, 
allow_nan=True, cls=None, indent=None, separators=None, 
encoding='utf-8', default=None, sort_keys=False, **kw) 

Serialize obj to a JSON formatted str.
序列化obj为一个json字符串!!!!!

三、load

load (fp, encoding=None, cls=None, object_hook=None, 
parse_float=None, parse_int=None, parse_constant=None, 
object_pairs_hook=None, **kw) 

Deserialize fp (a .read()-supporting file-like object containing a JSON document) to a Python object.
即:反序列化fp( 包含JSON结构的file-like object)为Python对象!!!!

如果fp的内容是基于ASCII编码而不是UTF-8(如latin-1)则必须指定encoding的名字,。编码是不允许不是基于ASCII编码的(如UCS-2),而应该用`codecs.getreader(fp)(encoding),或简单地解码为Unicode对象传递给loads()。

object_hook 是将要被一些对象逐字解码(一个dict)的结果调用的一个可选的函数。object_hook的返回值将用来代替dict。将来可以使用此功能来实现自定义解码器。

四、loads

loads (s, encoding=None, cls=None, object_hook=None, 
parse_float=None, parse_int=None, parse_constant=None, 
object_pairs_hook=None, **kw) 

Deserialize s (a str or unicode instance containing a JSON document) to a Python object.
即:反序列化s(一个JSON标准的str或者unicode实例)为Python对象。

如果s是一个str实例并且是基于ASCII编码而不是utf-8编码,则必须指定encoding的名字。 编码是不允许不是基于ASCII编码的(如UCS-2),并且首先解码为unicode。

五、JSON常见操作–dict、str相互转化

json.dumps()方法的功能是把Python对象变为JSON字符串。loads()反序列化JSON字符串为相应的Python对象。

>>> d = {"a": 1, "b": 2, "c": 3}
>>> import json
>>> str_d = json.dumps(d)
>>> print str_d, type(str_d)
{"a": 1, "c": 3, "b": 2} <type 'str'>
>>> d_trans = json.loads(str_d)
>>> print d_trans, type(d_trans)
{u'a': 1, u'c': 3, u'b': 2} <type 'dict'>
>>>

dump()方法的功能是把Python object写入到文件!注意到我们是写进一个file-like object而不是一个地址!load()对应为读取!

>>> d = {"a": 1, "c": 3, "b": 2}
>>> import json
>>> with open("C:\\Users\\admin\\Desktop\\111.txt", "w") as f:
  json.dump(d, f)


>>>
>>> with open("C:\\Users\\admin\\Desktop\\111.txt", "r") as f:
  d1 = json.load(f)


>>> d1
{u'a': 1, u'c': 3, u'b': 2}
>>>

with as语句的妙用:避免打开文件后手写关闭文件代码,避免人为忘记写f.close(),避免使用try–except–finally导致的大量代码!

欲了解更多,还可以参考:http://liuzhijun.iteye.com/blog/1859857
http://www.open-open.com/lib/view/open1363244182234.html

你可能感兴趣的:(json,python)