How to extract a field from this payload with a re

2019-09-24 07:19发布

问题:

This question already has an answer here:

  • Parse JSON with Python 2 answers

I have this payload that I wish to extract a field from:

{"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"}

The field I wish to extract is "amount":1, the 1 value in particular. I know that regex is the obvious way to go here, but it's so confusing to me! Should I be searching the string and using str[:::] indices instead? (Also: I changed all the values in this example but it's the exact format).

回答1:

Edit:

The data you provided is a JSON string. You can convert it to a dictionary using the json package:

import json

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

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

obj is a nested dictionary in this case, amount is a key in the subdictionary under the key donation_info



回答2:

You can do this

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

Simply put, before you use it as dictionary, you have to load this payload string as the data structure: dictionary.

Edit: My bad, there’s another layer, it should be

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

Ref python doc