Chinaunix首页 | 论坛 | 博客
  • 博客访问: 337278
  • 博文数量: 100
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 521
  • 用 户 组: 普通用户
  • 注册时间: 2014-10-31 11:37
个人简介

活到老,学到老

文章分类

全部博文(100)

文章存档

2018年(1)

2017年(2)

2016年(11)

2015年(82)

2014年(4)

我的朋友

分类: Python/Ruby

2016-08-07 20:50:38

json和python的数据格式的对应关系
JSON Python
object dict
array list
string str
number (int) int
number (real) float
true True
false False
null None

序列化json对象到文件 json.dump(obj, fp, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, default=None, sort_keys=False, **kw) 个别参数说明:
     indent设置为'/t',可以以缩进的形式写入文件。

序列化json对象到str json.dumps(obj, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, default=None, sort_keys=False, **kw)
将文件内容转换为json对象 json.load(fp, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, **kw)
将str内容转换为json对象
json.loads(s, encoding=None, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, **kw)
代码示例
  1. #!/usr/local/bin/python3
    #coding=utf-8
    
    import json
    
    def encodeJson():
        test1_contents_dict = {"a": 1,"b": 2 ,"c": 3}
        test2_contents_list=[4,5,6]
        test_contents_dict={"test1":test1_contents_dict,"test2":test2_contents_list}
        test_dict={"test":test_contents_dict}
    
        
        test_json_data=json.dumps(test_dict,sort_keys=True)
        print(test_json_data)
    
    
        with open('E:\\test.json', 'w') as f:
            json.dump(test_dict,f,indent='\t',sort_keys=True)
    
    def decodeJson():
        with open('E:\\test.json','r') as f:
            test_dict=json.load(f)
  2.     test_contents_dict=test_dict['test']
        print(test_contents_dict)
  3.     test1_contents_dict = test_contents_dict['test1']
        print(test1_contents_dict)
  4.     test2_contents_list=test_contents_dict['test2']
        print(test2_contents_list)
    
        #print(test_dict['test']['test1'])
        #print(test_dict['test']['test2'])
  5. if __name__ == '__main__':
        encodeJson()
        decodeJson()
    
输出json文件的内容:
    
  1. {
  2.     "test": {
  3.         "test1": {
  4.             "a": 1,
  5.             "b": 2,
  6.             "c": 3
  7.          },
  8.         "test2": [
  9.             4,
  10.             5,
  11.             6
  12.         ]
  13.     }
  14. }

:   
一开始我把源文件的名字命名json.py,结果编译的时候报错:“AttributeError: 'module' object has no attribute 'dumps”,原来文件命名与python的json模块命名冲突





阅读(1919) | 评论(0) | 转发(0) |
0

上一篇:libcurl在mac上编译

下一篇:cjson的基本使用

给主人留下些什么吧!~~