JSON.stringify() not escaping apostrophe - json

...using JSON2.js and JQUERY
as you can see from the first image the object property customerReport.Title has an apostrophe. In the code you can see that I'm calling JSON.stringify() into reportAsJson string which still has the unescaped apostrophe.
the error returned by $.ajax() is {"Message":"Invalid object passed in, \u0027:\u0027 or \u0027}\u0027 expected. ...
Initially I'm just going to ban apostrophe's from the user, but I thought JSON.stringify() handled this or do I need to set some option????
Thanks

You can avoid removing these apostrophes replacing them with an HTML entity ' - that's a single quot - and later decode HTML entities either in the client or server-side.

Following has worked for me after so many failed tries for stringify and other JSON parsing functions:
updatedString = string.replace(/('[a-zA-Z0-9\s]+\s*)'(\s*[a-zA-Z0-9\s]+')/g,"$1\\\'$2");
where
string = string having apostrophe in it.
updatedString = string with apostrophe issue resolved/escaped

Related

HTML5 localstorage adding in double quotes

I'm currently assigning the value of a field to a variable:
userName = document.getElementById('userName').value;
Then assigning that variable to localstorage:
localStorage.setItem('userName', JSON.stringify(userName));
Retrieving that item here:
var retrievedUserName = localStorage.getItem('userName');
Then trying to output the contents of the item into a HTML div:
document.getElementById("response-heading-name2").innerHTML = retrievedUserName;
...but when I check the HTML, it's outputting the string with double quotes around it: "My name"
Does anyone know why this is happening, and how I can stop the double quotes from appearing?
This has nothing to do with local storage.
The quotes are added when you convert the data structure to JSON with JSON.stringify.
You should convert the JSON back to a JavaScript data structure with JSON.parse after you retrieve it from local storage.
The point of using JSON is to ensure that what you store is a string because local storage can only store strings.
Since you are getting the value of an input, you know that it will be a string. So you could dispense with JSON altogether and not JSON.stringify it in the first place.
localStorage always store the string data with double quotes, when you are retrieving the same data you will get with double quotes. So just use JSON.parse to fix it.
var retrievedUserName = JSON.parse(localStorage.getItem('userName'));

Json : getting the unwanted result

I'm using json plugin to get the response in json.
But I m getting the unwanted result:
Here is what I get:
{"data":"[[\"service\",\"webservices\",\"document\"],[\"validation\",\"adapters\",\"server\"]]","records":25,"recordsTotal":75}
originally the data var in my action class is like this:
[["service","webservices","document"],["validation","adapters","server"]]
but json plugin adds the backslash.
The wanted result is that:
{"data":[["service","webservices","document"],["validation","adapters","server"]],"records":25,"recordsTotal":75}
Is there a way to get the later result ?
Thanks
You're representing the data as a PHP string. " is obviously a reserved character in JSON, so your serialization library is dutifully escaping the quote using /.
If you set up the PHP variable so it's an array of arrays, instead of a string representing an array of arrays, then your JSON serialization will work fine.

Text encoding problems in JSON.stringified() object

I have a index.html with a which sends a text to a PHP code. This PHP sends it again by POST (curl) to a Node.js server, inserted in a JSON message (utf8-encoded)
//Node.js server file (app.js) -- gets the json and shows it in a <script> to save it in client JS
render(index, {json:{string:"mystring"}})
//Template to render (index.ejs)
var data = <%=JSON.stringify(json)%>;
So that I can pass those variables in the JSON to data. JSON is way bigger than here, I wrote only the part which creates a bug : the string contained here makes an "INvalid character" JS bug. What should I do ? Which encoding/decoding/escaping should I use ?
I have utf-8 everywhere, as all my other strings work, even with german or arabic characters. In this particular case, this is the "mystring" below which breaks the app :
If I remove the characters in the red circles It works.
Here is the string as it is in the JSON i receive :
"Otto\nTheater-, Konzert- und Gpb\n\u2028\u2028Rhoasse\u00dfe 20\u2028\n51065 K\u00f6ln\n\nTelefon: 0000-000000-0\u2028\nTelefax: 0000-000000\n\nE-Mail: address#mail.com\u2028"
Because it is a user-entered text, I must handle this kind of characters. I don't have access to the PHP part of the code, only to the nodeJS and client JS. How can I find and remove/convert those chars in JS ?
<%- JSON.stringify(data).replace(/[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, "\\n") %>;
I ended up replacing invalid unicode characters (which are valid for JSON but not in JS code) with line breaks. This solves the problem
JSON is commonly thought to be a subset of JavaScript, but it isn't quite. Due to an unfortunate oversight, the raw characters U+2028 and U+2029 are permitted in JSON string literals, but not in JavaScript string literals. In JavaScript, they are interpreted as newlines and so having one in a string literal is a syntax error.
Consequently this:
var data = <%=JSON.stringify(json)%>;
isn't safe. You can make it so by manually replacing them with string-literal-escaped versions:
JSON.stringify(json).replace('\u2028', '\\u2028').replace('\u2029', '\\u2029')
Typically it's best to avoid this kind of problem, and keep code and data strictly separated, by dropping the JSON data into an HTML data- attribute. It can then be read out of the DOM from the client-side script and passed through JSON.parse. Then the only kind of escaping you have to worry about is normal HTML-escaping, which hopefully your templating language does by default.
The other characters in your answer are actually okay for JS string literals, except for the control characters, which JSON also escapes.
It may well make sense to remove some of these characters anyway, as an input filtering step. It's unusual and almost always undesirable to have cruft like U+2028 in your data. You could consider filtering out the characters unsuitable for use in markup which include U+2028/9 and other bad things like bidi overrides that can mess up your page rendering.

What is the correct way to post a colon in a querystring parameter?

I am posting a form and one of the field values has a ":" and that is causing an issue
is there any correct way to be able to post this string;
http://www.mysite.com/MyController/MyAction?field1=Japan:Tokyo&field2=USA:NewYork
You can use percent encoded version of colon "%3A"
Lots of libraries will have a method to process this, for example in ASP.NET if you do a UrlEncode that should get changed to a %3A, when you need to use it just do a UrlDecode on the string.
http://www.mysite.com/MyController/MyAction?field1=Japan%3ATokyo&field2=USA%3ANewYork
If you are not using any library that has this type of functionality then you can easily build your own little parsing function that will replace common characters with their HTML character code equivalent.

Why does JSON.parse("string") fail

According to the JSON spec a string is a legitimate JSON value.
So why does this happen?
You are actually passing the bare word string in to the the function which of course is not valid JSON. To actually pass in the value "string" you need to be careful with your JavaScript.
Try this:
JSON.parse("\"string\"")
The extra pair of quotes must be escaped so they become part of the value you pass in to the function.
The Syntax error tells you: "s" is an unexpected token. A string is a valid JSON value but as the spec describes it must be enclosed in double quotes.
string
""
" chars "
Generally, you can use JSON.stringify(myValue) to check what a properly formatted JSON string of such value would be.
Because a string in JSON must be surrounded by quotation marks, and in your JSON.parse("string") call, JSON.parse never "sees" any quotation marks as part of the text it is asked to parse. The double-quotes that we see are being used to form a legal string to pass in -- they're not part of the text we're passing in.
This call works:
JSON.parse('"s"')