Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to parse somewhat wrong JSON with Python?

I have a following JSON string coming from external input source:

{value: "82363549923gnyh49c9djl239pjm01223", id: 17893} 

This is wrong-formatted JSON string ("id" and "value" must be in quotes), but I need to parse it anyway. I have tried simplejson and json-py and seems they could not be set up to parse such strings.

I am running Python 2.5 on Google App engine, so any C-based solutions like python-cjson are not applicable.

Input format could be changed to XML or YAML, in adition to JSON listed above, but I am using JSON within the project and changing format in specific place would not be very good.

Now I've switched to XML and parsing the data successfully, but looking forward to any solution that would allow me to switch back to JSON.

like image 782
Serge Tarkovski Avatar asked Dec 19 '09 00:12

Serge Tarkovski


People also ask

How does Python handle JSON error?

The Python "json. decoder. JSONDecodeError: Extra data" occurs when we try to parse multiple objects without wrapping them in an array. To solve the error, wrap the JSON objects in an array or declare a new property that points to an array value that contains the objects.

How do you Analyse JSON data in Python?

Instead of the JSON loads method, which reads JSON strings, the method used to read JSON data in files is load(). The load() method takes up a file object and returns the JSON data parsed into a Python object. To get the file object from a file path, Python's open() function can be used.


1 Answers

since YAML (>=1.2) is a superset of JSON, you can do:

>>> import yaml >>> s = '{value: "82363549923gnyh49c9djl239pjm01223", id: 17893}' >>> yaml.load(s) {'id': 17893, 'value': '82363549923gnyh49c9djl239pjm01223'} 
like image 105
mykhal Avatar answered Sep 20 '22 01:09

mykhal