I have a textfield in a database that contains the results of a python json.dumps(list_instance)
operation. As such, the internal fields have a u'
prefix, and break the browser's JSON.parse()
function.
An example of the JSON string is
"density": "{u'Penobscot': 40.75222856500098, u'Sagadahoc':
122.27083333333333, u'Lincoln': 67.97977755308392, u'Kennebec':
123.12237174095878, u'Waldo': 48.02117802779616, u'Cumberland':
288.9285325791363, u'Piscataquis': 3.9373586457405247, u'Hancock':
30.698239582715903, u'Washington': 12.368718341168325, u'Aroostook':
10.827378163074039, u'York': 183.47612497543722, u'Franklin':
16.89330963710371, u'Oxford': 25.171240748402518, u'Somerset':
12.425648288323485, u'Knox': 108.48302300109529, u'Androscoggin':
208.75502815768303}"
What I'd like to do is replace those occurrences of u'
with a '
(single-quote). I've tried
function renderValues(data){
var pop = JSON.parse(data.density.replace(/u'/g, "'"));
}
but I'm always getting a unexpected token '
exception. Since many of the possible key fields may contain a u
, it is not feasable to just delete that character. How can I find all instances of u'
and replace with '
without getting the exception?
The accepted solution is wrong. Your code fails because that string is not valid JSON. Fixing the pseudo-JSON string by replacing it is wrong.
What you have to do is fix the python code that is producing that broken JSON string, which I am pretty sure it is a str() or unicode() where there should be nothing. What you have as a value for the key "density" is a string instead of a dictionary, and therefore, python returns you something like the following:
{"density": "a string that looks like JSON but it is in fact a string reprensentation of a dictionary"}
The function json.dumps
will return you always valid JSON strings.
Fix that and you will not have to hack around with filthy string replacements or whatever.
EDIT
Check the following snippet out. There you can see that the u'...' is just the python readable-representation of a unicode object, and has nothing to do whatsoever with a JSON serialization.
>>> import json
>>> data = {u'name': u'Manuel', u'age': 26}
>>> print data
{u'age': 26, u'name': u'Manuel'} # this is the python representation of a dictionary
>>> print json.dumps(data)
{"age": 26, "name": "Manuel"} # this is a valid JSON string
That JSON is not properly formed, as easy as that.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With