Reputation: 611
I'm catching a webhook from Stripe for invoices that succeed which provides me with this
amount: 7500
currency: usd
description: None
discountable: True
id: sub_DfLYbarfoo
livemode: True
metadata: {}
object: line_item
period: {u'start': 1537694450, u'end': 1569930450}
plan: {u'active': True, u'product': u'prod_Bzxbarfoo', u'transform_usage': None, u'name': u'Agent - Yearly', u'aggregate_usage': None, u'created': 1513986904, u'tiers_mode': None, u'interval': u'year', u'tiers': None, u'object': u'plan', u'id': u'ra-yearly', u'currency': u'usd', u'amount': 7500, u'interval_count': 1, u'trial_period_days': 2, u'livemode': True, u'usage_type': u'licensed', u'metadata': {u'qb_product': u'71'}, u'nickname': u'Agent - Yearly', u'statement_descriptor': u'foobar.com/charge', u'billing_scheme': u'per_unit'}
proration: False
quantity: 1
subscription: None
subscription_item: si_DfLYfoo
type: subscription
I want to extract the data from 'plan' and parse it for use in a Zapier process. I've narrowed down the exact data I need using the following code
data = input['data']
begin_index = data.find('plan:') + 6
end_index = data.rfind('}') + 1
plan = data[begin_index:end_index]
which provides me with
{u'active': True, u'product': u'prod_Bzxbarfoo', u'transform_usage': None, u'name': u'Agent - Yearly', u'aggregate_usage': None, u'created': 1513986904, u'tiers_mode': None, u'interval': u'year', u'tiers': None, u'object': u'plan', u'id': u'ra-yearly', u'currency': u'usd', u'amount': 7500, u'interval_count': 1, u'trial_period_days': 2, u'livemode': True, u'usage_type': u'licensed', u'metadata': {u'qb_product': u'71'}, u'nickname': u'Agent - Yearly', u'statement_descriptor': u'foobar.com/charge', u'billing_scheme': u'per_unit'}
I'm not sure what the leading 'u' characters is doing on each key and value, but it is preventing me from parsing this into usable json.
Upvotes: 0
Views: 307
Reputation: 38
You can try using ast.literal_val
which will return a python dict
. For example, in your code:
import ast
import json
data = input['data']
begin_index = data.find('plan:') + 6
end_index = data.rfind('}') + 1
plan = ast.literal_eval(data[begin_index:end_index])
json_plan = json.dumps(plan)
ast.literal_eval
simply parses the string as a literal (it does not execute any code, and thus safe to use, unlike eval). This string is a valid python dict
object. the "u" prefix marks a unicode
type in python pre python3.
Upvotes: 1