元组格式的python json数据不可解析

时间:2019-03-10 07:49:21

标签: python json

我很难理解为什么以下输出(应该是json格式,是从datbase查询生成的)不可解析。

Geometry.faces.push(new THREE.Face3(v0, v1, v2, [n0, n1, n2], vertexColor, materialIndex));

我不能像对待json一样对待它,因为当我对数据(直接从数据库)执行dbresponse = """ (('{"stopApprovalInd":true,"nonPersonalizedCardLine3":"Valued Cardholder","productRoutingBins":[{"requestType":"DIGITAL_ACCOUNT_REQUEST","bin":"342010002"}],"holdtimeSeconds":0,"defaultUpcInd":"false","updatedTimestamp":"2019-01-23T18:53:26.261Z","productName":"PB EGIFT (CAG) MAYO\'S $100","reloadMaxAmount":0,"issuerCompanyCode":"BKPB","updaterId":"IIKIFFFFFFPDZ0PDNQBGWMVGMRVTK9DM","sellStartDate":"2018-08-20T00:00:00.000+0000","taxIncludedInd":false,"taxPercent":0,"maxValueAmount":100,"proxyCardLength":19,"inventorySource":"BLAST","postReversalInd":false,"distributionChannel":"DIGITAL","multicardFlag":"N","companyCode":"BKPB","indentDataType":"0","activateOnShipment":"false","productRedemptionMethods":[],"upc":"07675030446","productFees":[{"feeAmount":0,"feeType":"PURCHASE"},{"feeAmount":0,"feeType":"TRANSACTION"},{"feeAmount":0,"feeType":"CUSTOMIZATION"}],"cpDivisionId":"2X2A9M5KRLXQWQ1SB","subGroupId":"YVAAN33PV7MZ3Z49V0F0J","defaultProductConfigurationId":"Y56X4RXNCY2R9ACSDH","isContentEnabled":false,"productFulfillments":[{"fulfillmentMethod":"EMAIL","fulfillmentType":"PRINT_ON_DEMAND"}],"taxAmount":0,"redeemLocationInd":false,"taxableInd":false,"productRedemptionLocations":[],"generationType":"0","serviceCode":"121","processorCompanyCode":"HP","productDisplayname":"MAYO\'s $100 eGift","baseValueAmount":100,"creatorId":"IIKIFFFFFFPDZ0PDNQBGWMVGMRVTK9DM","subsequentActivation":false,"generateProxyCardNumberInd":false,"productCategory":"CLOSELOOP","exclusionInd":false,"reloadableInd":false,"reversibleInd":false,"productLocale":[{"redemptionInstructions":"<p>Your E-gift Card is redeemable online at mayo.com and in \'s stores nationwide.<\\/p>","productTemplates":[{"templateType":"PRODUCTION","templateId":"Z6WSTWN9HABX8","templatePath":"https://blahblah.net/gcmimages/View/WGNX8/index.html"}],"localeCode":"en_US","inStoreInstructions":"<p>In Store: Print this entire page, and present it to a Mayo\'s Associate at checkout.<\\/p>","onlineInstructions":"<p>Online: Enter your E-Gift Card Number at checkout in the PAY WITH GIFT CARD box. If you have any questions, or to check your balance, please call 1-800-511-2752.<br>You may also scan your printed barcode at a price checker terminal in stores.<br>Your Mayo\'s E-Gift Card number is required for all inquiries.<\\/p>","productDescription":"Mayo\'s, the largest retail brand of Mayo\'s, Inc. (NYSE:M), delivers fashion and affordable luxury to customers at approximately 670 locations in 45 states, the District of Columbia, Puerto Rico and Guam, as well as to customers in the U.S. and more than 100 international destinations through its leading online store at macys.com. Via its stores, e-commerce site, mobile and social platforms, Mayo\'s offers distinctive assortments including the most desired family of exclusive and fashion brands for him, her and home. Mayo\'s is known for such epic events as Mayo\'s 4th of July Fireworks\xae and the Mayo\'s Thanksgiving Day Parade\xae. Building on a more than 150-year tradition, and with the collective support of customers and employees, Mayo\'s helps strengthen communities by supporting local and national charities giving more than $69 million each year to help make a difference in the lives of our customers","termsAndConditions":"Your Mayo\'s E-Gift Card number may be used to purchase any merchandise on-line at macys.com or in-store by following the instructions in the E-Gift Card email. You may not add value back onto the E-Gift Card, nor redeem it for cash or apply it as payment or credit to your credit card account. When you make a purchase with your E-Gift Card number, the value of your purchase plus any shipping/handling fees and sales tax, if applicable, will be automatically deducted from your \\"open to buy.\\" You may check any remaining value via the online Balance Inquiry function, or in-store by scanning the barcode at a price checker terminal or by calling 1-800-511-2752. Please safeguard your Mayo\'s E-Gift Card number. The bearer is responsible for its loss or theft. If your E-Gift Card is lost or stolen, and you have proof of purchase, we will issue you a replacement for the balance shown on our records. Your macys.com E-Gift Card number is required for all inquiries."}],"cardExpirationType":"0","productBarcodes":[{"barcodeType":"1D-CA128"}],"feeStrippingInd":false,"productLineId":"3G2D6R3YG85WZ570","createdTimestamp":"2018-08-20T18:53:46.435Z","inventoryLoadType":"HOT","variableInd":false,"isForcedResponseProduct":false,"reloadMinAmount":0,"entityId":"6APACRYFLXTLSKS","itemBuyerGroupId":"FASHION","provisioningType":"DIGITAL","productFulfillmentPartners":[],"currencyCode":"USD","proxyBin":"0"}',),) """ 时,python告诉我它是一个“元组”数据。但是我知道,为了使我能够访问值,python需要将数据视为type(dbresponse)

我尝试将其转换为多种方式,但都无济于事。

dict

我对json不太了解。

我的问题是,是否有一种万无一失的方法来将上述数据从元组转换为字典?完成后,如何遍历数据中的所有键/值,以便查看可用的内容。

我尝试过str(dbresponse) eval(dict(dbresponse)) str(list(dbresponse)) # tried to convert it to a list, then to a str in hopes of then being able to convert it to dictionary. didnt work. (漂亮的打印纸),但对我来说还不太清楚(我可能使用不正确)。

3 个答案:

答案 0 :(得分:2)

如果您的回复确实是一个如此处所示的字符串,并且始终具有相同的格式,则可以在开头(('到末尾',),)删除。其余的是有效的JSON字符串:

import json

dbresponse = """(('{"stopApprovalInd":true,"nonPersonalizedCardLine3":"Valued Cardholder","productRoutingBins":[{"requestType":"DIGITAL_ACCOUNT_REQUEST","bin":"342010002"}],"holdtimeSeconds":0,"defaultUpcInd":"false","updatedTimestamp":"2019-01-23T18:53:26.261Z","productName":"PB EGIFT (CASHSTAR) MACY\'S $100","reloadMaxAmount":0,"issuerCompanyCode":"BKPB","updaterId":"IIKIFFFFFFPDZ0PDNQBGWMVGMRVTK9DM","sellStartDate":"2018-08-20T00:00:00.000+0000","taxIncludedInd":false,"taxPercent":0,"maxValueAmount":100,"proxyCardLength":19,"inventorySource":"BLAST","postReversalInd":false,"distributionChannel":"DIGITAL","multicardFlag":"N","companyCode":"BKPB","indentDataType":"0","activateOnShipment":"false","productRedemptionMethods":[],"upc":"07675030446","productFees":[{"feeAmount":0,"feeType":"PURCHASE"},{"feeAmount":0,"feeType":"TRANSACTION"},{"feeAmount":0,"feeType":"CUSTOMIZATION"}],"cpDivisionId":"2X2A9M5KRLXQWQ1SB","subGroupId":"YVAAN33PV7MZ3Z49V0F0J","defaultProductConfigurationId":"Y56X4RXNCY2R9ACSDH","isContentEnabled":false,"productFulfillments":[{"fulfillmentMethod":"EMAIL","fulfillmentType":"PRINT_ON_DEMAND"}],"taxAmount":0,"redeemLocationInd":false,"taxableInd":false,"productRedemptionLocations":[],"generationType":"0","serviceCode":"121","processorCompanyCode":"HP","productDisplayname":"Macy\'s $100 eGift","baseValueAmount":100,"creatorId":"IIKIFFFFFFPDZ0PDNQBGWMVGMRVTK9DM","subsequentActivation":false,"generateProxyCardNumberInd":false,"productCategory":"CLOSELOOP","exclusionInd":false,"reloadableInd":false,"reversibleInd":false,"productLocale":[{"redemptionInstructions":"<p>Your E-gift Card is redeemable online at macys.com and in Macy\'s stores nationwide.<\\/p>","productTemplates":[{"templateType":"PRODUCTION","templateId":"Z6WSTWN9HABX8","templatePath":"https://blahblah.net/gcmimages/View/WGNX8/index.html"}],"localeCode":"en_US","inStoreInstructions":"<p>In Store: Print this entire page, and present it to a Macy\'s Associate at checkout.<\\/p>","onlineInstructions":"<p>Online: Enter your E-Gift Card Number at checkout in the PAY WITH GIFT CARD box. If you have any questions, or to check your balance, please call 1-800-511-2752.<br>You may also scan your printed barcode at a price checker terminal in stores.<br>Your Macy\'s E-Gift Card number is required for all inquiries.<\\/p>","productDescription":"Macy\'s, the largest retail brand of Macy\'s, Inc. (NYSE:M), delivers fashion and affordable luxury to customers at approximately 670 locations in 45 states, the District of Columbia, Puerto Rico and Guam, as well as to customers in the U.S. and more than 100 international destinations through its leading online store at macys.com. Via its stores, e-commerce site, mobile and social platforms, Macy\'s offers distinctive assortments including the most desired family of exclusive and fashion brands for him, her and home. Macy\'s is known for such epic events as Macy\'s 4th of July Fireworks\xae and the Macy\'s Thanksgiving Day Parade\xae. Building on a more than 150-year tradition, and with the collective support of customers and employees, Macy\'s helps strengthen communities by supporting local and national charities giving more than $69 million each year to help make a difference in the lives of our customers","termsAndConditions":"Your Macy\'s E-Gift Card number may be used to purchase any merchandise on-line at macys.com or in-store by following the instructions in the E-Gift Card email. You may not add value back onto the E-Gift Card, nor redeem it for cash or apply it as payment or credit to your credit card account. When you make a purchase with your E-Gift Card number, the value of your purchase plus any shipping/handling fees and sales tax, if applicable, will be automatically deducted from your \\"open to buy.\\" You may check any remaining value via the online Balance Inquiry function, or in-store by scanning the barcode at a price checker terminal or by calling 1-800-511-2752. Please safeguard your Macy\'s E-Gift Card number. The bearer is responsible for its loss or theft. If your E-Gift Card is lost or stolen, and you have proof of purchase, we will issue you a replacement for the balance shown on our records. Your macys.com E-Gift Card number is required for all inquiries."}],"cardExpirationType":"0","productBarcodes":[{"barcodeType":"1D-CA128"}],"feeStrippingInd":false,"productLineId":"3G2D6R3YG85WZ570","createdTimestamp":"2018-08-20T18:53:46.435Z","inventoryLoadType":"HOT","variableInd":false,"isForcedResponseProduct":false,"reloadMinAmount":0,"entityId":"6APACRYFLXTLSKS","itemBuyerGroupId":"FASHION","provisioningType":"DIGITAL","productFulfillmentPartners":[],"currencyCode":"USD","proxyBin":"0"}',),)"""

json_str = dbresponse[3:-5]
data = json.loads(json_str)
print(data)

# {'stopApprovalInd': True, 'nonPersonalizedCardLine3': 'Valued Cardholder', 'productRoutingBins': [{'requestType': 'DIGITAL_ACCOUNT_REQUEST', 'bin': '342010002'}], 'holdtimeSeconds': 0, 'defaultUpcInd': 'false', 'updatedTimestamp': '2019-01-23T18:53:26.261Z', 'productName': "PB EGIFT (CASHSTAR) MACY'S $100", 'reloadMaxAmount': 0, 'issuerCompanyCode': ...

print(data['stopApprovalInd'])
# True

答案 1 :(得分:1)

内部内容似乎包装在单引号'中,但包含未转义的单引号(例如"MAYO'S")。这当然是语法错误。

尽管有几种逃避级别,但生成内容的代码仍无法正确处理。

但是Thierry发现,删除前4个和后6个字符会留下有效的JSON(在这种情况下),您可以使用json.loads(dbresponse[4:-6])对其进行解析。

答案 2 :(得分:0)

为支持其他类型的输入,我们可以使用findrfind

import json
# dbresponse = ...
begin = dbresponse.find("'")
end = dbresponse.rfind("'")

data = json.loads(dbresponse[begin+1:end])