Python解析JSON格式
Python解析具有相似JSON格式的字符串方法如下:
# -*- coding: utf-8 -*- # Author: areful class BaseResponse(object): rspType = "" rspCode = "" rspDesc = "" def parse_json(self, _json): _header = BaseResponse() try: _res_dict = eval(_json) _header.__dict__.update(_res_dict["header"], encoding="utf-8", ensure_ascii=False) self.__dict__.update(_res_dict["body"], encoding="utf-8", ensure_ascii=False) return _header, self except Exception: _header.rspCode = 999 return _header, self class User(BaseResponse): id = "" class Customer(BaseResponse): name = "" if __name__ == '__main__': json_str_user = '{"header":{"rspType":"0","rspCode":"0"}, "body":{"id":"3a43e147bdaa9eab19ad25e7ea281d29"}}' header, user = User().parse_json(json_str_user) print(user.id) json_str_custom = '{"header":{"rspType":"0","rspCode":"0"}, "body":{"name":"Lee Si"}}' header, custom = Customer().parse_json(json_str_custom) print(custom.name)
- 上一篇 »Java使用JSONPath解析JSON完整内容详解
- 下一篇 »【Python】xml 解析