I'm having an issue with the parser of jQuery when I give him a JSON string like this (java):
String JSONvalue = "[{"evaluationId":92688,"ResponseId":378501,"comment":"I can't do this ~!##$%^&*()_+|}{\":?><\/.,;'[]\\=-0987654321`","rankingId":0}]";
and when I pass it to the parser (javascript), it looks like this:
var prevCommentsAndRankings = jQuery.parseJSON('[{"evaluationId":92688,"ResponseId":378501,"comment":"I can't do this ~!##$%^&*()_+|}{\":?><\/.,;'[]\\=-0987654321`","rankingId":0}]');
I'm getting error of invalid tokens, this is because of the ' " and [ ] on the JSON string. How could I handle them, consider that the JSON may always have special characters within. Thanks in advance !
Just for the arbitrary strings replace the quote with it's HTML entity " BEFORE rendering it in JSON and right after you parsed the JSON. Both are common function you can find in Java and Javascript.
Related
I think this is a basic question, but I can't understand the reason. in JSON, it's valid to has a special character like "asdfadf\tadfadf", but when try parse it, it's shown error.
eg. code:
let s = '{"adf":"asdf\tasdfdaf"}';
JSON.parse(s);
Error:
Uncaught SyntaxError: Bad control character in string literal in JSON at position 12
at JSON.parse (<anonymous>)
at <anonymous>:1:6
I need to understand what is the issue, and solution.
You have to take into account that \t will be involved in two parsing operations: first, when your string constant is parsed by JavaScript, and second, when you parse the JSON string with JSON.parse(). Thus you must use
let s = '{"adf":"asdf\\tasdfdaf"}';
If you don't, you'll get the error you're seeing from the actual tab character embedded in the string. JSON does not allow "control" characters to be embedded in strings.
Also, if the actual JSON content is being created in server-side code somehow, it's probably easier to skip building a string that you're immediately going to parse as JSON. Instead, have your code build a JavaScript object initializer directly:
let s = { "adf": "asdf\tasdfdaf" };
In your server environment there is likely to be a JSON tool that will allow you to take a data structure from PHP or Java or whatever and transform that to JSON, which will also work as JavaScript syntax.
let t = '{"adf":"asdf\\tasdfdaf"}';
var obj = JSON.parse(t)
console.log(obj)
This question already has answers here:
Parsing string as JSON with single quotes?
(10 answers)
Closed 1 year ago.
var str = "{'a':'Your's'}";
JSON.parse(str);
My server response like above string. Not able to parse as JSON. It is as example text. While am parsing I got error as below:
JSON.parse(str);
VM1951:1 Uncaught SyntaxError: Unexpected token ' in JSON at position 1(…)(anonymous function) # VM1950:1
The same question already raised by someone. click here to see. But, not helpful. Please help on this. Thanks in advance.
TL;DR JSON only supports double quotes.
Please fix the error on the server, if this is possible.
JSON required double quotes, the single quotes are therefore not conform to the standard. There may be parsers, that support them anyway, but you can never rely on that. For more details on the JSON syntax, you may have a look at http://www.json.org/.
Besides this, the input string "{'a':'Your's'}"; is totally invalid itself, if the single quotes would be valid. The ' in Your's is breaking the string literal, the following s is outside the string and the next ' is opening a string, that contains } but is never closed by another '.
The correct syntax would be '{"a":"Your\'s"}'.
If you received the string and cannot correct the server output, you may try to replace all ' by ", but you will have problems with single quotes inside your payload strings. By far the easiest - and most stable(!) - fix should be correcting the server output instead of correcting the defect output on the client.
Converting on the client with the following code may be a good idea at the first thought, but would corrupt payload strings with single quotes in it.
replaceInString = function(fullString, search, replacement) {
return fullString.split(search).join(replacement);
};
var json = replaceInString("{'a':'Your's'}", "'", '"');
If you can be sure, there are no whitespace characters outside the payload and also there are no line breaks, you could use the following function. But also only, if you are sure, the search patterns are not in the payload strings.
var json = "{'a':'Your's'}";
replaceInString = function(fullString, search, replacement) {
return fullString.split(search).join(replacement);
};
json = replaceInString(json, "{'", '{"');
json = replaceInString(json, "'}", '"}');
json = replaceInString(json, "':", '":');
json = replaceInString(json, ":'", ':"');
json = replaceInString(json, "',", '",');
json = replaceInString(json, ",'", ',"');
json = replaceInString(json, "['", '["');
json = replaceInString(json, "']", '"]');
But using this code, e.g. the JSON `following JSON string would be corrupted.
{'mathTerm':'x=1-[2+A']'}
To be clear: Code like this gets you over a bump on the road to develop , test or learn something. But this is not a durable fix. Contact the server developer to fix his implementation and remove your client side fix before going to production.
JSON keys and values must be enclosed in double quotes (") instead of single quotes (')
This is correct:
var str = '{"a":"Your\'s"}';
JSON.parse(str);
I have json on my page coming from the string property of the model:
var myJson = '[{\"A\":1,\"B\":10,\"C\":\"214.53599548339844\",\"D\":\"72.52798461914062\"},
{\"A\":1,\"B\":11,\"C\":\"214.53599548339844\",\"D\":\"72.52798461914062\"}]'
I want to process that json via javascript on the page
I am doing $.parseJSON(#Html.Raw(Json.Encode(myJason))); but json still contain \" symbol. If i do $.parseJSON(#Html.Raw(Json.Decode(myJason))); it is just producing an $.parseJSON(System.Web.Helpers.DynamicJsonArray); How can I fix that?
Take your JSON and .stringify() it. Then use the .replace() method and replace all occurrences of ("\").
var myString = JSON.stringify(myJson);
var myNewString = myString.replace(/\\/g, "");
Hope this helps.
There are two ways
1 from where you get the JSON asked them to send you as url encoded format. at your end you need to decode url and you will get the Perfect JSON.
Other wise do the laborious replace method for each and every special charecter with respective char.
like above example you need to use replace("\","");
There is no JSON parser that will be able to deal with a JSON string that isn't properly formatted in the first place.
so you need to make sure that your theModel is formatted appropriately and according JSON.org standards.
Like
Koushik say you can use String operation
Since the JSON format specifies that single quotes should not be escaped, most libraries (or even the native JSON parser) will fail if you have an escaped single quote in it. Now this usually is not a problem since most of the time you do an XHR that fetches some data formatted as JSON and you use the responseText which contains your JSON string that you can then parse, etc.
In this particular situation, I have a JSON string stored in a database as text... so the database contains something like {"property":"value"} and I want to output this as part of an HTML page created by the server so that the JavaScript code in that page looks something like this:
var x = '{"property":"value"}';
Now if the JSON string in the database contains a single quote like this:
{"property":"val'ue"}
Then I need to escape it or else I will never be able to use it as a string:
console.clear();
var obj = {prop:"val'ue"};
var str = JSON.stringify(obj);
console.log("JSON string is %s",str);
console.dir(JSON.parse(str)); //No problem here
//This obviously can't work since the string is closed and it causes an invalid script
//console.dir(JSON.parse('{prop:"val'ue"}'));
//so I need to escape it to use a literal JSON string
console.dir(JSON.parse('{"prop":"val\'ue"}'));
The question then is why {"prop":"val\'ue"} not considered a valid JSON string ?
In JavaScript - the string '{"prop":"val\'ue"}' is a correct way to encode the JSON as a string literal.
As the JavaScript interpreter reads the single-quoted string, it will convert the \' to '. The value of the string is {"prop":"val'ue"} which is valid JSON.
In order to create the invalid JSON string, you would have to write '{"prop":"val\\\'ue"}'
If I understand the question right, you are trying to generate JavaScript code that will set some variable to the decoded version of a JSON string you have stored in the database. So now you are encoding the string again, as the way to get this string into JavaScript is to use a string literal, passing it through JSON.parse(). You can probably rely on using the server side JSON encoder to encode the JSON string as a JavaScript string literal. For instance:
<?php $jsonString = '{"prop":"val\'ue"}'; ?>
var myJson = JSON.parse(<?php echo json_encode($jsonString) ?>);
// Prints out:
// var myJson = JSON.parse("{\"prop\":\"val'ue\"}");
// And results: Object - { prop: "val'ue"}
However, If you are 100% sure the JSON is going to be valid, and don't need the weight of the extra parsing / error checking - you could skip all that extra encoding and just write:
var myJson = <?php echo $jsonString; ?>
Remember, JSON is valid JavaScript syntax for defining objects after all!
According to jsonlint it is valid without escaping the single quote, so this is fine:
{"prop": "val'ue"}
But this is invalid:
{"prop":"val\'ue"}
According to json.org json:
is completely language independent but
uses conventions that are familiar to
programmers of the C-family of
languages, including C, C++, C#, Java,
JavaScript, Perl, Python, and many
others
So it is the language conventions in c-type languages regarding the reverse solidus (\) that means that your example is not valid.
You might try the following, however, it's ugly.
JSON.parse("{\"obj\":\"val'ue\"}");
Or just store the string to a var first. This should not store the literal backslash value and therefore the JSON parser should work.
var str = '{"obj" : "val\'ue"}';
JSON.parse(str);
I am using sun.misc.BASE64Encoder to encode an encrypted value, which is then added to a JSON field and subsequently sent to the client. I use Javascript's eval() function on the client to create an object from the JSON code. When eval() runs, it gives the error:
unterminated string literal
There are other fields in the JSON code, but I've narrowed the error specifically to the base64 encoded field. Here's the offending line of javascript code:
var result = eval( '(' + xhr.responseText + ')' );
Here's the JSON object from the Servlet:
{
'resource':'resource?Signature=j79r/2Hly+HqhS/6fdd+prfsR+kUNijUvDN0QJ14ZR43gzYScOMDypt/crks/CEphTUXVptJvSol
1ZOOvScCUhNOCb7dZk/3MKnI5tOewSACXK32/OJNd8hYpZtSTn+WhA6+f9BUIUZWA83U8Cud/Tb8V
R1yQWbDGG/mM/NiUSiY=',
'url':'http://somesite.com/pr'
}
I'm not sure why eval is dying, but it seems the value of the 'resource' JSON field contains something it doesn't care for.
Thanks in advance.
Tim
I think it may be because your JSON appears to have line breaks in it. If you remove them, does it work?