如何用正则表达式从这个有效负载中提取字段?

2024-10-02 14:27:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个要从中提取字段的有效负载:

{"encrypted_sender_transaction_id":"514658451","donation_info":{"tid":321654658,"ppgf_donation_id":4654564,"pp_transaction_id":19446119405222584,"nonprofit_id":6454,"amount":1,"gross_amount":1,"currency_code":"USD","type":"U","party_id":"2313654","product_type":"DN","is_recurring":false,"transaction_time":"2018-06-04","donor_name":"Foo Bar","donor_email_address":"foo.bar@foobar.com","is_donor_sharing_contact":true,"product_description":"PayPal Donations with PPGF","partner_name":"PayPal","receiver_transaction_id":13214,"encrypted_transaction_id":"4564","receiver_account_number":"123","methodof_donation":"4001","encrypted_pptxn_id":"123","update":false},"payout_date":"2018-06-25","charity_type":"PPGF","charity_info":{"name":"Comic Relief Red Nose Day","address":{"line1":"123 Foobar Ave, 123th Floor","line2":"","city":"New York","state":"NY","postal_code":"123123","country_code":"US","phone":"123418","latitude":"123.45675876","longitude":"-7213.97493"},"state":"Confirmed","confirmation_date":"2016-04-19","logo_url":"https://pics.paypal.com/00/s/Mjg0ZDUwOWMtY2U3ZS00NjVhLWJkMDUtMGE2Y2RiZDIxODc4/file.JPG","mission_area":[{"id":1015,"name":"Philanthropy, Grants, Other","is_primary":true},{"id":1012,"name":"Human Services","is_primary":false}],"adhoc_ppgf":false,"mission":"Philanthropy, Grants, Other"},"payout_status":1,"isResult":true,"convertedpytdate":"Jun 25, 2018","convertedtransactdate":"Jun 4, 2018","transaction_id":"43934096XX104234C"}

我想提取的字段是"amount":1,尤其是1值。我知道正则表达式是一种很明显的方法,但它让我很困惑!我应该搜索字符串并使用str[:::]索引吗?(另外:我更改了本例中的所有值,但格式完全相同)。你知道吗


Tags: nameinfoidfalsetrueistypedonation
2条回答

你能做到的

import json
data = json.loads(payload)
amount = data[‘amount’]

简单地说,在将其用作字典之前,必须将此有效负载字符串作为数据结构加载:dictionary。你知道吗

编辑: 我的错,还有一层,应该是

amount = data[‘donation_info’][‘amount’]

参考python doc

编辑:

您提供的数据是一个JSON字符串。您可以使用json包将其转换为字典:

import json

payload = u'{"encrypted_sender_transaction_id":"514658451",...}'
obj = json.loads(payload)

print obj['donation_info']['amount']
# 1

obj是嵌套字典在本例中,amount是键donation_info下的子字典中的键

相关问题 更多 >