Google App Engine - Parsing Json -From a Form - Python

The hosting provider I'm dealing with can send alerts in a format they call

"POST some JSON-encoded data to a URL"

Here is a code fragment that I'm using to interpret the alert.

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)

And this is the response

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

How do I parse this to JSON?

Upvotes: 2

Views: 37

Answers (2)

timgeb
timgeb

Reputation: 78780

Let s be your string.

>>> 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]"}'

The problem is that this is still not valid JSON because the beginning 21T08:07:50+00:00", is borked. You could manually correct it, or leave the first entry out.

>>> 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'}

Upvotes: 1

Bhargav
Bhargav

Reputation: 918

If it is JSON, then just use the json module in python.

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))

Upvotes: 0

Related Questions