python解析json字符串

#coding=utf-8 

import json
from pprint import *
from jsonpath_rw import jsonpath, parse
#import simplejson
#import demjson
try:
    import xml.etree.cElementTree as ET
except ImportError:
    import xml.etree.ElementTree as ET

json_content = """
{
	"A": "root A",
	"B": "root B",
	"C": {
		"A": "CA",
		"B": "CB",
		"C": "CC",
		"D": "CD"
	},
	"D": [{
		"A": "DA1",
		"B": "DB1",
		"C": "DC1",
		"D": "DD1"
	},
	{
		"A": "DA2",
		"B": "DB2",
		"C": "DC2",
		"D": "DD2"
	}],
	"result": {
		"A": "result A",
		"B": "result B",
		"C": {
			"A": "result CA",
			"B": "result CB",
			"C": "result CC",
			"D": "result CD"
		},
		"D": [{
			"A": "result DA1",
			"B": "result DB1",
			"C": "result DC1",
			"D": "result DD1"
		},
		{
			"A": "result DA2",
			"B": "result DB2",
			"C": "result DC2",
			"D": "result DD2"
		}]
	}
}
"""

json_relation = """<items>
	<item interfacename='OUTA' tagname='a'/>
	<item interfacename='OUTB' tagname='b'/>
	<item interfacename='OUTC' tagname='C'/>
	<item interfacename='OUTD' tagname='D'/>
</items>
"""

doctor_content = """
{
  "Response": {
    "ResultCode": "0",
    "ErrorMsg": "1",
    "List": {
      "Item": [
        {
          "DoctorID": "13121",
          "DoctorName": "李师师",
          "RegTypeID": "1",
          "RegScheduleCode": "12",
          "FeeType": "药事二级医院挂号费",
          "ScheduleTime": "全日(08:00-07:59)",
          "RegCount": "187",
          "LimitCount": "200",
          "DoctorLevel": "主任医师",
          "TotalCost": "11.5",
          "List1": {
            "Item1": [
              {
                "FeeID": "80100",
                "FeeName": "药事二级医院挂号费",
                "Unit": "次",
                "Number": "1.00",
                "Price": "1.50",
                "ShouldMoney": "1.50",
                "ActualMoney": "1.50"
              },
              {
                "FeeID": "80101",
                "FeeName": "门(急)诊药事服务费",
                "Unit": "人次",
                "Number": "1.00",
                "Price": "10.00",
                "ShouldMoney": "10.00",
                "ActualMoney": "10.00"
              }
            ]
          }
        },
        {
          "DoctorID": "13121",
          "DoctorName": "李师师",
          "RegTypeID": "1",
          "RegScheduleCode": "12",
          "FeeType": "药事二级医院挂号费",
          "ScheduleTime": "全日(08:00-07:59)",
          "RegCount": "187",
          "LimitCount": "200",
          "DoctorLevel": "主任医师",
          "TotalCost": "11.5",
          "List1": {
            "Item1": [
              {
                "FeeID": "80102",
                "FeeName": "药事二级医院挂号费",
                "Unit": "次",
                "Number": "1.00",
                "Price": "1.50",
                "ShouldMoney": "1.50",
                "ActualMoney": "1.50"
              },
              {
                "FeeID": "80103",
                "FeeName": "门(急)诊药事服务费",
                "Unit": "人次",
                "Number": "1.00",
                "Price": "10.00",
                "ShouldMoney": "10.00",
                "ActualMoney": "10.00"
              }
            ]
          }
        }
      ]
    }
  }
}
"""

doctor_relation = """<items>
	<item interfacename='OUTFeeID' tagname='FeeID'/>
	<item interfacename='OUTFeeName' tagname='FeeName'/>
	<item interfacename='OUTUnit' tagname='Unit'/>
	<item interfacename='OUTNumber' tagname='Number'/>
    <item interfacename='OUTPrice' tagname='Price'/>
    <item interfacename='OUTShouldMoney' tagname='ShouldMoney'/>
    <item interfacename='OUTActualMoney' tagname='ActualMoney'/>
</items>
"""

def ParseJson(request):
    jsonObj = JsonObject()
    return jsonObj.EnParseJson(request)

class JsonObject:
    'Json操作类 2017-08-01/yx'

    #入参校验
    def __CheckRequest(self, request):
        if 'strContent' not in request.keys():
            raise BaseException('strContent field is not find')
        if 'strMappingRelation' not in request.keys():
            raise BaseException('strMappingRelation field is not find')
        if 'strParseitemFlag' not in request.keys():
            raise BaseException('strParseitemFlag field is not find')

    #获取映射关系
    def __GetRelation(self, relation):
        dict = {}
        try:
            items = ET.fromstring(relation)
        except BaseException as e:
            return None
        for item in items.findall('item'):
            infname = item.get('interfacename')
            tagname = item.get('tagname')
            if infname and tagname:
                dict[infname] = tagname
        return dict if dict else None
    
    #获取给定字典给定key的值,多层节点用'/'分隔: root/child1/child2
    def __GetChildDict(self, text, tagflag):
        childtext   = text
        tagList     = tagflag.split("/")
        for i in range(len(tagList)):
            childparam = tagList[i]
            if isinstance(childtext, dict):
                for (k, v) in childtext.items():    
                    if childparam.lower() == str(k).lower():
                        childtext = v
                        break
        return childtext

    def __GetJsonPathList(self, text, jsonPath):
        jsonpath_expr = parse(jsonPath)
        recordList = [match.value for match in jsonpath_expr.find(text)]
        return recordList

    #组合输出集合
    def __GroupResponse(self, dict_rel, dict_record, list_response):
        item = {}
        for (k, v) in dict_rel.items():
            value = ''
            for (m, n) in dict_record.items():
                if str(v).lower() == str(m).lower():
                    value = str(n)
                    break
            if value != '':
                item[k] = value
        if item:
            list_response.append(item)

    #解析Json字符串
    def EnParseJson(self, request):
        self.__CheckRequest(request)
        sContent            = request['strContent']
        sMappingrelation    = request['strMappingRelation']
        sParseitemflag      = request['strParseitemFlag']
        response            = []

        dict_rel = self.__GetRelation(sMappingrelation)
        if dict_rel is None:
            raise BaseException('parse json sting has no mapping relation.')
        
        try:
            text = json.loads(sContent)
            #text = simplejson.loads(content)
            #text = demjson.decode(content)
        except BaseException as e:
            raise BaseException(e.message)
        
        if sParseitemflag == "":
            if isinstance(text, dict): 
                self.__GroupResponse(dict_rel, text, response)
            return response
        
        #result = self.__GetChildDict(text, sParseitemflag)
        result = self.__GetJsonPathList(text, sParseitemflag)
        if isinstance(result, list):
            for i in result:
                record = i
                if isinstance(record, dict):
                    self.__GroupResponse(dict_rel, record, response)
        elif isinstance(result, dict):
            self.__GroupResponse(dict_rel, result, response)
        return response

"""
###########解析Json函数入参说明###########
strContent:         待解析的Json字符串
strMappingRelation: 接口出参节点和待解析的Json节点之间的映射关系,以xml的形式传入
strParseitemFlag:   待解析的主节点标识
"""
if __name__ == "__main__":
    try:
        request = {}
        request['strContent']          = json_content
        request['strMappingRelation']  = json_relation

        request['strParseitemFlag']    = '$'
        print("1:root")
        pprint(ParseJson(request))

        request['strParseitemFlag']    = '$.C'
        print("\n2:C")
        pprint(ParseJson(request))

        request['strParseitemFlag']    = '$.D[*]'
        print("\n3:D")
        pprint(ParseJson(request))

        request['strParseitemFlag']    = '$.result'
        print("\n4:result")
        pprint(ParseJson(request))

        request['strParseitemFlag']    = '$.result.C'
        print("\n5:result/C")
        pprint(ParseJson(request))

        request['strParseitemFlag']    = '$.result.D[*]'
        print("\n6:result/D")
        pprint(ParseJson(request))

        request['strContent']          = doctor_content
        request['strMappingRelation']  = doctor_relation
        request['strParseitemFlag']    = '$.Response.List.Item[*].List1.Item1[*]'
        print("\n6:doctor")
        pprint(ParseJson(request))
    except BaseException as e:
        print(e.message)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值