json.dumps loads 终于区分出来了

来源:互联网 发布:蚁群算法matlab 编辑:程序博客网 时间:2024/05/23 18:31
[python] view plain copy
 print?
  1.   

每次遇到json loads/dumps始终搞不清方向,写段代码试下:

[python] view plain copy
 print?
  1. import json  
  2.   
  3. dict_ = {1:23:4"55":"66"}  
  4.   
  5. # test json.dumps  
  6.   
  7. print type(dict_), dict_  
  8. json_str = json.dumps(dict_)  
  9. print "json.dumps(dict) return:"  
  10. print type(json_str), json_str  
  11.   
  12. # test json.loads  
  13. print "\njson.loads(str) return"  
  14. dict_2 = json.loads(json_str)  
  15. print type(dict_2), dict_2  

程序结果:

<type 'dict'> {'55': '66', 1: 2, 3: 4}
json.dump(dict) return:
<type 'str'> {"55": "66", "1": 2, "3": 4}


json.loads(str) return
<type 'dict'> {u'55': u'66', u'1': 2, u'3': 4}


总结:

json.dumps : dict转成str

json.loads:str转成dict

如此简单。

0 0
原创粉丝点击