Why is it that
//Code
JSON.parse("{'name':'Khushal Khan'}");
results in this error
//Resposnse
SyntaxError: Unexpected token '
while this works perfectly
//Code
JSON.parse('{"name":"Khushal Khan"}');
Output:
//Response
Object {name: "Khushal Khan"}
The problem is the type of quote used in your JSON string, not the outer quotes. The JSON specification only allows for double quoted strings. You could use either type of quote to actually pass your JSON string to the parse() function, though.
From the JSON spec:
The problem is not that your JavaScript string uses " characters but that your JSON strings do not.
JSON is not JavaScript. JSON strings must be delimited by " characters.
From the specification:
string = quotation-mark *char quotation-mark
and
quotation-mark = %x22 ; "
Problem is not with double quoted string, but the json should have no single quotes as delimiters.
I have below string
'[{\'Question\': \'a Names and Roles (if known)\'}]'
I need to convert it into JSON.
I tried JSON.parse(s)
I got error SyntaxError: Unexpected token ' in JSON at position 2
and also
> eval(s)
SyntaxError: Unexpected string
Any help would be really appreciable
Problem is that you need to pass string inside JSON.parse(s).
Please make sure s is a string
'[{*Question\': at the point of asterisk you need a \' don't you?
So it should be
'[{\'Question\': \'a Names and Roles..
EDIT
Found this after a bit of research. Problem is with the single quote. Replace them with double quotes, you are good to go. See this fiddle, to check this out in action.
Additionally, I had to modify "[\'NA\']" in your string, to get it to working. That is also invalid JSON. If it is an array that you want it to be, you should put it like [\"NA\"].
I'm trying to parse a String to JSON in NodeJS/Javascript, this is my string (which I cannot change, coming from an external database):
'{\\"value1\\":\\"XYZ\\",\\"value2\\":\\"ZYX\\"}'
I'm calling:
JSON.parse(row.raw_data)
But are getting:
SyntaxError: Unexpected token \ in JSON at position
I actually thought double escape was the correct way of escaping in string/JSON.
Your JSON is invalid. You've said you can't change it, which is unfortunate.
It looks like it's been double-stringified but then the outermost quotes have been left off. If so, you can fix it by adding " at each end and then double-parsing it, like this:
var str = '{\\"value1\\":\\"XYZ\\",\\"value2\\":\\"ZYX\\"}';
str = '"' + str + '"';
var obj = JSON.parse(JSON.parse(str));
console.log(obj);
Ideally, though, you'll want to go through the database and correct the invalid data.
I actually thought double escape was the correct way of escaping in string/JSON.
In JSON, strings are wrapped in double quotes ("), not double escapes. You only escape double quotes within strings (with a single \).
If you've been creating JSON strings manually (in code), don't. :-) Instead, create the structure you want to save, and then stringify it. Building JSON strings manually is error-prone, but a proper JSON stringifier will be reliable.
Why is it that
//Code
JSON.parse("{'name':'Khushal Khan'}");
results in this error
//Resposnse
SyntaxError: Unexpected token '
while this works perfectly
//Code
JSON.parse('{"name":"Khushal Khan"}');
Output:
//Response
Object {name: "Khushal Khan"}
The problem is the type of quote used in your JSON string, not the outer quotes. The JSON specification only allows for double quoted strings. You could use either type of quote to actually pass your JSON string to the parse() function, though.
From the JSON spec:
The problem is not that your JavaScript string uses " characters but that your JSON strings do not.
JSON is not JavaScript. JSON strings must be delimited by " characters.
From the specification:
string = quotation-mark *char quotation-mark
and
quotation-mark = %x22 ; "
Problem is not with double quoted string, but the json should have no single quotes as delimiters.
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.
Updated solution: replace(/u'/g, "'")); => replace(/u'(?=[^:]+')/g, "'"));.
Tested with the following:
"{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'Timbuktu': 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}".replace(/u'(?=[^:]+')/g, "'");
results in:
"{'Penobscot': 40.75222856500098, 'Sagadahoc': 122.27083333333333, 'Lincoln': 67.97977755308392, 'Kennebec': 123.12237174095878, 'Waldo': 48.02117802779616, 'Cumberland': 288.9285325791363, 'Piscataquis': 3.9373586457405247, 'Hancock': 30.698239582715903, 'Timbuktu': 12.368718341168325, 'Aroostook': 10.827378163074039, 'York': 183.47612497543722, 'Franklin': 16.89330963710371, 'Oxford': 25.171240748402518, 'Somerset': 12.425648288323485, 'Knox': 108.48302300109529, 'Androscoggin': 208.75502815768303}"
a little bit old in the answer but if there is no way to change or access the server response try with:
var strExample = {'att1':u'something with u'};
strExample.replace(/u'[\}|\,]/g, "ç'").replace(/u'/g, "'").replace(/ç'/g, "u'");
//{'att1':'something with u'};
The first replace will handle the u' that are in the trailing part of the string in the object changing it to 'ç' character
then removing the u from the phyton unicode and finally change it to u' like the original
I had a similar issue and made this regex that found all of the u's even if the values had them too.
replace(/(?!\s|:)((u)(?='))/g, "")
The accepted answer, I found, missed these occurrences.
I know the OP's doesn't have 'u' for the values and only for keys but thought this may be useful too :)