How to Deal with Malformed JSON

Posted on
Sun Nov 27, 2016 7:38 pm
Bollar offline
Posts: 528
Joined: Aug 11, 2013

How to Deal with Malformed JSON

The JSON returned by the Roomba I'm trying to communicate with is malformed and causes a ValueError exception when using requests.json() or json.loads(). Does anyone have an idea on how to fix/filter/resolve the problem?

Here's a sample string:
Code: Select all
{"ok":{"d":"sun","h":19,"m":22},"id":1"}}
and another:
Code: Select all
{"ok":{"flags":0,"cycle":"none","phase":"charge","pos":{"theta":-90,"point":{"x":-495,"y":792}},"batPct":96,"expireM":0,"rechrgM":0,"error":0,"notReady":0,"mssnM":514,"sqft":999},"id":1"}}

Regardless, they all fail with this error:
Code: Select all
 Error: Parse error on line 21:
...": 999   },   "id": 1 "}}
---------------------^
Expecting 'EOF', '}', ',', ']', got 'undefined'

Insteon / Z-Wave / Bryant Evolution Connex /Tesla / Roomba / Elk M1 / SiteSage / Enphase Enlighten / NOAA Alerts

Posted on
Sun Nov 27, 2016 9:04 pm
jay (support) offline
Site Admin
User avatar
Posts: 18221
Joined: Mar 19, 2008
Location: Austin, Texas

Re: How to Deal with Malformed JSON

There appear to be 2 problems: the extra quote after the 1 at the end - it doesn't match any other quote, and the extra closing brace at the end. You can attempt to fix those very specific issues, but it seems likely there will be other issues as well. I would contact Roomba and complain that their API is just broken...

Jay (Indigo Support)
Twitter | Facebook | LinkedIn

Posted on
Sun Nov 27, 2016 9:11 pm
Bollar offline
Posts: 528
Joined: Aug 11, 2013

Re: How to Deal with Malformed JSON

jay (support) wrote:
...their API is just broken...

Their API is just unpublished... Hence the workarounds. Any advice?

Insteon / Z-Wave / Bryant Evolution Connex /Tesla / Roomba / Elk M1 / SiteSage / Enphase Enlighten / NOAA Alerts

Posted on
Sun Nov 27, 2016 9:41 pm
matt (support) offline
Site Admin
User avatar
Posts: 21417
Joined: Jan 27, 2003
Location: Texas

Re: How to Deal with Malformed JSON

If the problem is always that on the end there is:

"}}

But there should be just:

}

Then you could try parsing the JSON, then if there is the exception you could hack the raw JSON string to force the "}} to be a }, then re-run the parser on it?

Image

Posted on
Sun Nov 27, 2016 9:46 pm
Bollar offline
Posts: 528
Joined: Aug 11, 2013

Re: How to Deal with Malformed JSON

Ah.
Code: Select all
r = requests.post(post_url, json=payload, headers=head, verify=False)

broken = str(r.text)
fixed = broken.replace('"''}','')

Results:
Code: Select all
   Script                          {"ok":{"d":"sun","h":21,"m":45},"id":1"}}
   Script                          {"ok":{"d":"sun","h":21,"m":45},"id":1}

Insteon / Z-Wave / Bryant Evolution Connex /Tesla / Roomba / Elk M1 / SiteSage / Enphase Enlighten / NOAA Alerts

Page 1 of 1

Who is online

Users browsing this forum: No registered users and 10 guests