读取json响应,选择密钥并将其转换为csv

时间:2018-11-04 17:59:40

标签: json python-2.6

我正在尝试从REST API生成的json中读取一些键。我们的服务器上没有安装熊猫,所以我不能使用json_normalize并且python版本是2.6.6。

我将从文件中读取数据。因此,首先设置将使用json.load加载:

import json 
with open('response.json','r') as f:
    data = json.load(f)

现在,我正在尝试循环每个响应并从中选择值。

示例响应:

data = [{
   "status":    [
            {
         "type": "Claims",
         "code": "000",
         "severity": "Success",
         "message": "Claim was processed successfully",
         "correlationId": "20b74d33-2fc5-4283-8732-393bdf2877b2#12230"
      },
            {
         "type": "Claims",
         "code": "4006",
         "severity": "Warning",
         "message": "AUTH No UM pre-authorizations match  (line 1)",
         "correlationId": "20b74d33-2fc5-4283-8732-393bdf2877b2#12230"
      },
            {
         "type": "Claims",
         "code": "4006",
         "severity": "Warning",
         "message": "ADD FLN TO ATTACHMENT SCREEN  (line 1, 2)",
         "correlationId": "20b74d33-2fc5-4283-8732-393bdf2877b2#12230"
      }
   ],
   "claimsHeader":    {
      "claimId": "18GM10618600",
      "subscriberId": "114848120",
      "groupId": "LABYHP",
      "claimType": {"code": "M"},
      "claimSubType": {"code": "M"},
      "currentStatus": {"code": "01"},
      "statusSeqNo": 1,
      "lastActionDt": "2018-11-02T11:00:34",
      "inputDate": "2018-11-02T00:00:00",
      "receivedDt": "2018-11-02T00:00:00",
      "acceptDate": "2018-11-02T11:00:34",
      "lowServiceDate": "2018-07-30T00:00:00",
      "hiServiceDate": "2018-07-30T00:00:00",
      "clsProdCategory": {"code": "M"},
      "prdApplicationId": "$SC5",
      "classID": {"code": "LA32"},
      "classPlanId": {"code": "LACAID"},
      "productId": {"code": "LACAID"},
      "familyInd": {"code": "C"},
      "planEntryDate": "2017-11-01T00:00:00",
      "memberAge": 26,
      "memberRelation": {"code": "M"},
      "gender": "F",
      "memRecordNo": "00014353290",
      "provRelPfx": {"code": "CAID"},
      "serviceBenDefn": {"code": "LA01"},
      "processingAgent": {"code": "LACD"},
      "networkId": {"code": "LANETWORK"},
      "agreementId": {"code": "LACDPROF0005"},
      "assignmentInd": {"code": "P"},
      "payeeProvInd": "002911440501",
      "releaseInfoInd": "N",
      "otherBenefits": "N",
      "accidentAmt": "0.0000",
      "similarIllDt": "2018-07-30T00:00:00",
      "providerId": "002754207001",
      "networkInd": {"code": "I"},
      "pcpIndicator": "N",
      "pcpProvId": "006492307002",
      "patientPaidAmt": "0.0000",
      "totalChargeAmt": "1000.0000",
      "totalPayable": "125.0000",
      "chkCycleOvr": {"code": "S"},
      "dragDate": "2018-11-09T00:00:00",
      "inputMethod": "W",
      "adminEobInd": "A",
      "clinicalEdtInd": {"code": "7"},
      "capitationInd": {"code": "N"},
      "agreementSrc": {"code": "R"},
      "productType": {"code": "D"},
      "provAddrTyp": "002",
      "processAuditInd": "Y",
      "hsaIndicator": {"code": "N"},
      "clmMultiFunction": [      {
         "serviceProvNpi": "1821089822",
         "serviceProvTax": "262221423",
         "icdVerProcessed": {"code": "0"},
         "inpIcdVersionInd": {"code": "0"}
      }],
      "clmSecondary": [{"totAmountApply": "0.0000"}],
      "claimLineDetail":       [
                  {
            "claimLineNo": 1,
            "lineOfBusiId": "LA01",
            "lobIndicator": {"code": "1"},
            "servicePymtPfx": {"code": "LAA1"},
            "limitPrefix": {"code": "LA01"},
            "servicePricingId": {"code": "NTWX"},
            "serviceId": {"code": "IXO"},
            "serviceRule": {"code": "NOA"},
            "placeOfService": {"code": "11"},
            "procedureCode": {"code": "H0015U8"},
            "diagnosisCode": {"code": "F1120"},
            "subDiagnosisCd": {"code": "F1120"},
            "relatedDiagId": "F11",
            "svcLineFromDt": "2018-07-30T00:00:00",
            "svcLineToDt": "2018-07-30T00:00:00",
            "chargedAmt": "500.0000",
            "hcpcsRate": "0.0000",
            "considerChgAmt": "500.0000",
            "clmLineAllowAmt": "0.0000",
            "clmLineUnits": 1,
            "unitsAllow": 0,
            "lineDeductAmt": "0.0000",
            "dedAccumAccnt": 0,
            "copayAmount": "0.0000",
            "coinsAmount": "0.0000",
            "riskWithholdAmt": "0.0000",
            "paidAmount": "0.0000",
            "disallowAmt": "500.0000",
            "disallowRsn": {"code": "PXN"},
            "agreementPrice": "125.0000",
            "profilePrice": "0.0000",
            "procTblPrice": "0.0000",
            "servicePrice": "0.0000",
            "discountAmt": "0.0000",
            "supplDiscountAmt": "0.0000",
            "itsDiscountAmt": "0.0000",
            "pricingIndicator": {"code": "A"},
            "relatedNtwInd": {"code": "I"},
            "referralIndic": {"code": "N"},
            "preAuthIndic": {"code": "V"},
            "capitatedInd": {"code": "N"},
            "subsPymtAmt": "0.0000",
            "provPymtAmt": "0.0000",
            "prePaidAmt": "0.0000",
            "referralSvcSeq": 0,
            "preAuthSvcSeq": 0,
            "preAuthSource": {"code": "S"},
            "placeOfSvcInd": {"code": "O"},
            "oopCalcBase": "500.0000",
            "ambuPymtCls": "0",
            "extLineNo": 0,
            "totPatientLiab": "0.0000",
            "patntDisllwLiab": "0.0000",
            "lineCrossRefData": [            {
               "fsaClmExpense": "0.0000",
               "fsaPaidAmt": "0.0000",
               "fsaDisallowCd": {"code": "060"},
               "reimburseInd": {"code": "N"}
            }],
            "lineDisallowData":             [
                              {
                  "disallowType": {"code": "PI"},
                  "disallowAmount": "375.0000",
                  "explanationCd": {"code": "PXN"}
               },
                              {
                  "disallowType": {"code": "SE"},
                  "disallowAmount": "125.0000",
                  "explanationCd": {"code": "A02"}
               }
            ],
            "claimLineSuppData": [            {
               "wholeClmPointer": 0,
               "encounterValue": "0.0000",
               "encntrStopLossAmt": "0.0000",
               "encntrNetValue": "0.0000"
            }]
         },
                  {
            "claimLineNo": 2,
            "lineOfBusiId": "LA01",
            "lobIndicator": {"code": "1"},
            "servicePymtPfx": {"code": "LA01"},
            "limitPrefix": {"code": "LA01"},
            "servicePricingId": {"code": "NTWX"},
            "serviceId": {"code": "REOM"},
            "serviceRule": {"code": "100"},
            "placeOfService": {"code": "11"},
            "procedureCode": {"code": "H2017U8"},
            "diagnosisCode": {"code": "F1120"},
            "subDiagnosisCd": {"code": "F1120"},
            "relatedDiagId": "F11",
            "svcLineFromDt": "2018-07-30T00:00:00",
            "svcLineToDt": "2018-07-30T00:00:00",
            "chargedAmt": "500.0000",
            "hcpcsRate": "0.0000",
            "considerChgAmt": "500.0000",
            "clmLineAllowAmt": "125.0000",
            "clmLineUnits": 1,
            "unitsAllow": 1,
            "lineDeductAmt": "0.0000",
            "dedAccumAccnt": 0,
            "copayAmount": "0.0000",
            "coinsAmount": "0.0000",
            "riskWithholdAmt": "0.0000",
            "paidAmount": "125.0000",
            "disallowAmt": "375.0000",
            "disallowRsn": {"code": "PXN"},
            "agreementPrice": "125.0000",
            "profilePrice": "0.0000",
            "procTblPrice": "0.0000",
            "servicePrice": "0.0000",
            "discountAmt": "0.0000",
            "supplDiscountAmt": "0.0000",
            "itsDiscountAmt": "0.0000",
            "pricingIndicator": {"code": "A"},
            "relatedNtwInd": {"code": "I"},
            "referralIndic": {"code": "N"},
            "preAuthIndic": {"code": "N"},
            "capitatedInd": {"code": "N"},
            "subsPymtAmt": "0.0000",
            "provPymtAmt": "125.0000",
            "prePaidAmt": "0.0000",
            "referralSvcSeq": 0,
            "preAuthSvcSeq": 0,
            "placeOfSvcInd": {"code": "O"},
            "oopCalcBase": "125.0000",
            "ambuPymtCls": "0",
            "extLineNo": 0,
            "totPatientLiab": "0.0000",
            "patntDisllwLiab": "0.0000",
            "lineCrossRefData": [            {
               "fsaClmExpense": "0.0000",
               "fsaPaidAmt": "0.0000",
               "fsaDisallowCd": {"code": "060"},
               "reimburseInd": {"code": "N"}
            }],
            "lineDisallowData": [            {
               "disallowType": {"code": "PI"},
               "disallowAmount": "375.0000",
               "explanationCd": {"code": "PXN"}
            }],
            "claimLineSuppData": [            {
               "wholeClmPointer": 0,
               "encounterValue": "0.0000",
               "encntrStopLossAmt": "0.0000",
               "encntrNetValue": "0.0000"
            }]
         }
      ]
   }
}]

对于每个响应,我必须从[claimLineDetail]中选择ClaimId,claimeLineNo,protocolPrice,capitatedInd

我需要获取这些值并将其放入csv文件中以进行进一步处理。 如果我遍历值:

for element in data :
    for key in element['claimsHeader']['claimLineDetail']:
        print key['claimLineNo'],key['agreementPrice'],key['capitatedInd']['code'] 

output :

1 125.0000 N
2 125.0000 N

我应该如何在每一行中添加ClaimId?以及将以上输出转换为字典格式的最佳方法是什么,以便我可以使用DictWriter使用以下代码将这些记录写入csv。

with open(outfile, 'w') as f:
    for element in data: 
        flat_data = #output of above#
        csvwriter = DictWriter(f,flat_data[0].keys(),lineterminator='\n')
        csvwriter.writerows(flat_data)

1 个答案:

答案 0 :(得分:0)

只需将element['claimsHeader']['claimId']添加到print。如果您只想逐行将循环的输出写入文件,请使用文件操作将其包装:

with open(outfile, 'wb') as f:
    for element in data:
        for key in element['claimsHeader']['claimLineDetail']:
            outputline = element['claimsHeader']['claimId']+" "+str(key['claimLineNo'])+" "+key['agreementPrice']+" "+key['capitatedInd']['code']+"\n"
            f.write(outputline.encode('latin-1'))
            print outputline