【问题标题】:How to extract a field from this payload with a regex? [duplicate]如何使用正则表达式从此有效负载中提取字段? [复制]
【发布时间】:2018-06-04 21:31:46
【问题描述】:

我有这个负载,我希望从中提取一个字段:

{"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[:::] 索引吗? (另外:我更改了此示例中的所有值,但格式完全相同)。

【问题讨论】:

  • 为什么是正则表达式?它看起来像一个 JSON/Dictionary 类型的对象,我确信 python 支持它。
  • `("amount":[^,}]*)' 试试regex101.com

标签: python regex parsing


【解决方案1】:

编辑:

您提供的数据是 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下的子字典中的一个键

【讨论】:

  • E0001:invalid syntax (, line 19) 当我将 myamount 设置为 payload['amount'] 时抛出错误
  • 哇,这比我想象的要容易。非常感谢,直截了当,按预期工作。
【解决方案2】:

你可以这样做

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

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

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

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

参考python doc

【讨论】:

  • 说出为什么它不好,而不是仅仅投反对票!
  • 不是我的反对意见,但可能是因为 data['amount'] 不起作用,因为 JSON 定义了一个嵌套字典。
  • 是的,有道理
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-12-30
  • 2013-11-23
  • 2015-08-31
  • 1970-01-01
  • 1970-01-01
  • 2021-10-09
  • 2013-09-01
相关资源
最近更新 更多