我正在处理的托管服务提供商可以以他们称之为
的格式发送提醒“将一些JSON编码的数据发布到URL”
这是我用来解释警报的代码片段。
class panic(webapp2.RequestHandler):
def get(self):
self.response.out.write("A")
def delete(self):
self.response.out.write("B")
def post(self):
self.response.out.write(self.request.body)
这是回复
21T08%3A07%3A50%2B00%3A00%22%2C%22application_name%22%3A%22Application%20name%22%2C%22account_name%22%3A%22Account%20name%22%2C%22severity%22%3A %22critical%22%2C%22message%22%3A%22Apdex%20score%20fell%20below%20critical%20level%20of%200.90%22%2C%22short_description%22%3A%22%5Bapplication%20name%5D%20alert%20opened %22%2C%22long_description%22%3A%22Alert%20opened%20on%20%5Bapplication%20name%5D%3A%20Apdex%20score%20fell%20below%20critical%20level%20of%200.90%22%2C%22alert_url%22 %3A%22https%3A%2F%2Frpm.newrelic.com%2Faccounts%2F%5Baccount_id%5D%2Fapplications%2F%5Bapplication_id%5D%2Fincidents%2F%5Bincident_id%5D%22%7D
如何将其解析为JSON?
答案 0 :(得分:1)
让s
成为您的字符串。
>>> import urllib2
>>> unquoted = urllib2.unquote(s)
>>> unquoted
'21T08:07:50+00:00","application_name":"Application name","account_name":"Account name","severity":"critical","message":"Apdex score fell below critical level of 0.90","short_description":"[application name] alert opened","long_description":"Alert opened on [application name]: Apdex score fell below critical level of 0.90","alert_url":"https://rpm.newrelic.com/accounts/[account_id]/applications/[application_id]/incidents/[incident_id]"}'
问题是这仍然不是有效的JSON,因为开始21T08:07:50+00:00",
是不可靠的。您可以手动更正它,或保留第一个输入。
>>> import json
>>> json.loads('{' + unquoted[unquoted.find(',')+1:])
{u'severity': u'critical', u'account_name': u'Account name', u'short_description': u'[application name] alert opened', u'alert_url': u'https://rpm.newrelic.com/accounts/[account_id]/applications/[application_id]/incidents/[incident_id]', u'application_name': u'Application name', u'message': u'Apdex score fell below critical level of 0.90', u'long_description': u'Alert opened on [application name]: Apdex score fell below critical level of 0.90'}
答案 1 :(得分:0)
如果是JSON,那么只需在python中使用json
模块。
import json
class panic(webapp2.RequestHandler):
def get(self):
self.response.out.write("A")
def delete(self):
self.response.out.write("B")
def post(self):
self.response.out.write(json.loads(self.request.body))