最新消息:20210917 已从crifan.com换到crifan.org

【示例】Python中处理json的示例代码

JSON crifan 3795浏览 0评论

【背景】

之前只总结了,Python中内置支持Json库处理json:

【整理】什么是JSON+如何处理JSON字符串

但是却没给出示例代码。

此处给出示例代码,关于python中如何处理json的。

 

【Python中处理json的代码】

#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Function:
【示例】Python中处理json的示例代码
【示例】Python中处理json的示例代码
Version: 2013-06-23 Author: Crifan Li Contact: https://www.crifan.org/contact_me/ """ import json; def python_json(): print "--- 1. Demo json to object value (here is dict) ---"; inputJsonStr = """{"list":[{"ArticleId":7392749,"BlogId":1158641,"CommentId":2182295,"Content":"偶是来测试评论滴,哈哈","ParentId":0,"PostTime":"2分钟前","Replies":null,"UserName":"crifan","Userface":"http://avatar.csdn.net/E/D/E/3_crifan.jpg"},{"ArticleId":7392749,"BlogId":1158641,"CommentId":2182254,"Content":"mark__","ParentId":0,"PostTime":"52分钟前","Replies":null,"UserName":"mars_tl","Userface":"http://avatar.csdn.net/9/3/0/3_mars_tl.jpg"}],"page":{"PageSize":20,"PageIndex":1,"RecordCount":0,"PageCount":0},"fileName":"7392749"}"""; #print "inputJsonStr=",inputJsonStr; convertedDict = json.loads(inputJsonStr, "utf-8"); print "type(convertedDict)=",type(convertedDict); #type(convertedDict)= <type 'dict'> print "convertedDict=",convertedDict; # convertedDict= {u'list': [{u'UserName': u'crifan', u'PostTime': u'2\u5206\u949f\u524d', u'Userface': u'http://avatar.csdn.net/E/D/E/3_crifan # .jpg', u'Replies': None, u'Content': u'\u5076\u662f\u6765\u6d4b\u8bd5\u8bc4\u8bba\u6ef4\uff0c\u54c8\u54c8', u'ArticleId': 7392749, u'ParentI # d': 0, u'CommentId': 2182295, u'BlogId': 1158641}, {u'UserName': u'mars_tl', u'PostTime': u'52\u5206\u949f\u524d', u'Userface': u'http://ava # tar.csdn.net/9/3/0/3_mars_tl.jpg', u'Replies': None, u'Content': u'mark__', u'ArticleId': 7392749, u'ParentId': 0, u'CommentId': 2182254, u' # BlogId': 1158641}], u'page': {u'PageIndex': 1, u'PageCount': 0, u'PageSize': 20, u'RecordCount': 0}, u'fileName': u'7392749'} #now can output some field value filename = convertedDict['fileName']; print "filename=",filename; #filename= 7392749 # dictList = convertedDict['list']; # for eachDict in dictList: # print "eachDict=",eachDict; print "--- 2. Demo object value to json ---"; jsonStr = json.dumps(convertedDict); print "type(jsonStr)=",type(jsonStr); #type(jsonStr)= <type 'str'> print "jsonStr=",jsonStr; print "=== more about json can refer: docs.python.org/2/library/json.html ==="; if __name__ == '__main__': python_json()

 

【总结】

Python中处理json,还是非常方便的。

json转对象:

convertedObjVal = json.loads(inputJsonStr);

对象转json:

jsonStr = json.dumps(objValue);

都是非常方便的。

转载请注明:在路上 » 【示例】Python中处理json的示例代码

发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
93 queries in 0.192 seconds, using 23.41MB memory