Json String with comment out quotes in variable - javascript

I have a JSON string hardcoded in my Javascript.
valiJsonString = '{"ssss","ddddddddd\"ddd"}';
The DOM says -> {"ssss","ddddddddd"ddd"}
Can someone tell me why javascript replace my \" into " ?
// try to parse
valiJsonString secureEvalJSON (valiJsonString) //<-- error: jsonString is not valid
working example

"The DOM says" doesn't make much sense, as the DOM doesn't say anything. Do you mean the object browser in Firebug (or some other development console)?
Now, inside a string, \" is the quote character. You have to compensate for this escaping since you do not want it, but instead a verbatim slash.
So perhaps you want \\ followed by ", which is the slashed character followed by the quote character.
In addition, the given JSON looks like it ought to represent an array not an object, since you have no keys:
var str = '["ssss","ddddddddd\\"ddd"]';
The actual value of this JSON-format string inside your browser is now:
["ssss","ddddddddd\"ddd"]

\ is an escape character. try \\

If you want your string to come through escaped, then you need to escape your escape character:
valiJsonString = '{"ssss","ddddddddd\\"ddd"}';

I've added second \ (\ is escape char) and fixed lack of = and type of table {} vs []
http://jsfiddle.net/4wVaR/9/

Related

I got error : "missing) after argument list"

Got error:
missing ) after the argument list
$('.next-btn').append("<a class="actionsubmit" ng-click="onSubmit('hello.html')">Check</a>");
It looks like you need to escape special characters inside your append string,
$('.next-btn').append("<a class=\"actionsubmit\" ng-click=\"onSubmit('hello.html')\">Check</a>");
The error is generated by syntax issues.
Your Code:
$('.next-btn').append("<a class="actionsubmit" ng-click="onSubmit('hello.html')">Check</a>");
You cannot use " inside this string without escaping it. For example:
$('.next-btn').append("<a class=\"actionsubmit\" ng-click=\"onSubmit('hello.html')\">Check</a>");
Please read: https://www.w3schools.com/js/js_strings.asp
Because strings must be written within quotes, JavaScript will misunderstand this string:
var x = "We are the so-called "Vikings" from the north.";
The string will be chopped to "We are the so-called ". The solution to avoid this problem, is to use the backslash escape character. The backslash (\) escape character turns special characters into string characters.
Now you can also create the element in jQuery. Advised code:
var newA = $("<a>", {
class: "actionsubmit",
"ng-click": "onSubmit('hello.html')"
}).html("Check");
$('.next-btn').append(newA);
Hope that helps.

Why can't Javascript parse this JSON array from a string literal?

What I am trying to do is simple. Parse this array holding json objects into a Javascript array.
var merchantsJson = JSON.parse('[{"id":61693,"name":"Más"},{"id":61690,"name":"\u0027\u0022\u003C/div\u003E"}]');
But the unicode character \u003C seems to be breaking the parser. In the chrome console I see "Uncaught SyntaxError: Unexpected token <"
A little more info. The above is what the code is evaluated to. In reality the code contains a jsp expression.
var merchantsJson = JSON.parse('${jsonArr}');
If I remove the single quotes, there is no issue, but eclipse give me an "missing semicolon" error message. Is it possible to parse the array with the quotes as I am trying to do?
The interpolation of ${jsonArr} is already a JavaScript object. When you wrap it in '${jsonArr}' this turns it into a string and you have to use JSON.parse.
There's no need to make it a string. You can just do var merchantsArray = ${jsonArr}. JSON constructs are already interoperable with JavaScript code.
Because there's an extra " in your string literal that is encoded by \u0022:
> '[{"id":61693,"name":"Más"},{"id":61690,"name":"\u0027\u0022\u003C/div\u003E"}]'
[{"id":61693,"name":"Más"},{"id":61690,"name":"'"</div>"}]
In short, your JSON in the string is invalid. You would need to escape the unicode escape sequences for the quotes in the string literal ("'\u0022</div>"), by using
JSON.parse('[{"id":61693,"name":"Más"},{"id":61690,"name":"\u0027\\u0022\u003C/div\u003E"}]'
// ^
or escape the quote character ("'\"</div>"):
JSON.parse('[{"id":61693,"name":"Más"},{"id":61690,"name":"\u0027\\\u0022\u003C/div\u003E"}]');
// ^^
However, there actually is no need to use JSON at all. Just output a JS array literal into your code:
var merchantsJson = ${jsonArr};
Try to replace \u with \\u. If you don't, JSON parser receives already decoded Unicode, which created polluted JSON.
It's not because of \u003C, rather the \u0022 character is causing the issue, since it's a quotation mark and JavaScript treats it literally ending the string.
You need to escape that character: \\u0022 .
you have to use special character in your JSON string, you can escape it using \ character.
you need to replace \ with \\.
[{\"id\":61693,\"name\":\"Más\"},{\"id\":61690,\"name\":\"\\u0027\\u0022\\u003C/div\\u003E\"}]

Javascript .replace() of the character " with the characters \"

I am trying to pass a JSON string to a C# .exe as a command line argument, from Javascript as a node.js child-process. For the sake of argument my JSON looks something like this:
string jsonString = '{"name":"Tim"}'
The issue with passing this as a C# arg is that the double quotation marks must be retained if I hope to parse it in the C# code. As such, what I need to pass into the C# command line needs to look something like this, where I escape the double quotation mark:
string jsonStringEscaped = '{\"name\":\"Tim\"}'
The motivation for doing this is that it allows me to maintain a consistent object structure across the two languages, which is obviously highly desirable for me.
In order to achieve this, I am attempting to use the Javascript .replace() method prior to sending the argument to the C#, and to do this I use a simple RegEx:
string jsonStringEscaped = jsonString.replace(/\"/g,"\\\"")
Unfortunately, this returns something of the form '{\\"name\\":\\"Tim\\"}' which is useless to me.
I have tried variations on this:
string jsonStringEscaped = jsonString.replace(/\"/g,"\\ \"")
\\ returns '{\\ "name\\ ":\\ "Tim\\ "}'
string jsonStringEscaped = jsonString.replace(/\"/g,"\\\\")
\\ returns '{\\\\name\\\\:\\\\Tim\\\\}'
string jsonStringEscaped = jsonString.replace(/\"/g,"\\\")
\\ is invalid
string jsonStringEscaped = jsonString.replace(/\"/g,"\\\ ")
\\ returns '{\\ name\\ :\\ Tim\\ }'
I have tried variations where the second .replace() argument is contained within single quotation marks '' rather than double quotation marks "" with no success.
Can anyone tell me what I am doing wrong? Better yet, can anyone suggest a more efficient method for doing what I am trying to achieve?
Unless I'm misreading you, I think you're just trying to escape a character that doesn't need to be escaped in your regex (").
var jsonString = '{"name":"Tim"}'
var escaped = jsonString.replace(/"/g, '\\"');
// escaped == "{\"name\":\"Tim\"}"

Why does this JSON string fail to parse?

Maybe I just don't see it at the moment, but why does this JSON string fail to parse? It should be valid.
var content = $.parseJSON('{"foobar" : "hallo\"tow"}');
Working example: http://jsfiddle.net/w6yjpame/2/
Because you're creating that JSON in a string literal, you need to escape the \ itself:
var content = $.parseJSON('{"foobar" : "hallo\\"tow"}');
console.log(content);
Explanation:
In JSON, " characters are escaped using \ characters. That makes the following perfectly valid JSON:
{"foobar" : "hallo\"tow"}
Now, in your example, you were constructing this JSON value within a JavaScript string:
'{"foobar" : "hallo\"tow"}'
This introduces a subtle issue, due to the fact that JavaScript strings also escape " characters with \ characters. That is, the following string literal:
'\"'
... holds the value:
"
Now, applying that to your example again, we find that this string literal:
'{"foobar" : "hallo\"tow"}'
... actually holds the value:
{"foobar" : "hallo"tow"}
As you can see, we've lost our \. Fortunately, this is easy to work around, as \ characters can also be escaped with \ characters in JavaScript strings, which is what my solution does. So now, the revised string literal:
'{"foobar" : "hallo\\"tow"}'
gets parsed as a string holding the intended value:
{"foobar" : "hallo\"tow"}
... which can then be parsed as properly formatted JSON.
The reason you don't have this issue when reading from a textarea or as the result of an ajax request is that the JSON value isn't being defined by a string literal. The extra \ is only required due to string literal syntax, and the competition going on for who's going to escape the " quote first (well, not really a competition... the string literal always wins).

How to add "\" character in JSON?

I want to add JSON data with the following string value:
json = "d:\xyz\abc";
This value is coming from a database at runtime. When I am going to display it in datatable, JSON formatting error is displayed. My requirement is that the above value will be displayed as it is in the datatable. Please help.
Escape it with another \:
var json = "d:\\xyz\\abc";
You'd better use a JSON library for your programming language. You don't retrieve database values directly with jquery, aren't you?
So, you'd use something like JSON.escape(my_string_from_db), or, in Ruby language I usually do my_string.to_json.
This will automatically escape everything that needs to be escaped.
Change to this:
json = "d:\\xyz\\abc";
See this question for further information
\ is the escape character in JavaScript strings, it gives special meaning to the character following the slash. Like \t is a tab character, \n is a new line. To put a backslash literal you'll need to use \\
The first backslash says the next character is going to be special, the following backslash says "oh, it's just a backslash."

Categories