Search code examples
pythonjsongoogle-app-enginepython-2.7webapp2

Comma in json string causes json.loads to fail with "Unterminated string starting at:"


This is my test command:

curl -v -A 'TEST/1.0' -X POST -d 'events=[{"event":"reset", "test":"reset;123"}]' 'http://127.0.0.1:8080/_api'

This is my RequestHandler

   class MyWebhookHandler(webapp2.RequestHandler):
     def post(self):
         events_json = self.request.get('events')
         event_datum = json.loads(events_json) # exception here

Whenever I reach the json.loads line, I got this exception:

    event_datum = json.loads(events_json)
  File "/usr/local/Cellar/python/2.7.9/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/__init__.py", line 338, in loads
    return _default_decoder.decode(s)
  File "/usr/local/Cellar/python/2.7.9/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/decoder.py", line 366, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/usr/local/Cellar/python/2.7.9/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/decoder.py", line 382, in raw_decode
    obj, end = self.scan_once(s, idx)
ValueError: Unterminated string starting at: line 1 column 27 (char 26)

What can I do to stop this exception?

EDIT

The problem is probably has more to do with self.request.get('events') than the json library. The function call returns

[{"event":"reset", "test":"reset

Instead of

[{"event":"reset", "test":"reset;123"}]

Solution

  • You are sending in your request a list, not a string events=[{"event":"reset", "test":"reset;123"}] you should use

    '{"events":[{"event":"reset", "test":"reset;123"}]}'