gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 21:57:59 25 4
gpt4 key购买 nike

我很难理解为什么以下输出(应该是 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"}',),)
"""

我不能将其视为 json,因为当我对数据(直接来自数据库)执行 type(dbresponse) 时,python 告诉我它是一个“元组”数据。但我知道为了能够访问这些值,Python 需要将数据视为字典。

我尝试了多种不同的方式来转换它,但都无济于事。

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.

我对json了解不多。

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

我尝试了 pprinnt ( pretty-print ),但这对我来说不太清楚(我可能使用不正确)。

最佳答案

如果您的响应确实是一个字符串,如下所示,并且始终具有相同的格式,您可以删除开头的 (('',),) 在最后。其余部分是有效的 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

关于元组格式的python json数据不可解析,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55085607/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com