Serialize for JavaScript apex - javascript

I need to serialize some simple object from .NET to JavaScript...
But I've some problem with apex...
C# example
var obj = new { id = 0, label = #"some ""important"" text" };
string json1 = Newtonsoft.Json.JsonConvert.SerializeObject(obj);
string json2 = Newtonsoft.Json.JsonConvert.SerializeObject(obj,
new Newtonsoft.Json.JsonSerializerSettings()
{
StringEscapeHandling = Newtonsoft.Json.StringEscapeHandling.EscapeHtml
});
JavaScript example
var resJson1= JSON.parse('{"id":0,"label":"some \"important\" text"}');
var resJson2= JSON.parse('{"id":0,"label":"some \u0022important\u0022 text"}');
Both parse give me the same error
VM517:1 Uncaught SyntaxError: Unexpected token I in JSON at position
23 at JSON.parse(<anonymous>)
Where am I wrong?

You're pasting the generated string of JSON into a JavaScript string constant without escaping it further. Try
console.log('{"id":0,"label":"some \"important\" text"}');
You'll see {"id":0,"label":"some "important" text"} i.e. the "important" quotes are no longer escaped by backslashes. (And you'll get the same for your \u0022 example too.) If you want to paste in the backslashes you'll have to escape them again:
var resJson1= JSON.parse('{"id":0,"label":"some \\"important\\" text"}');
The JSON you've generated with a single backslash would be fine if read from a file or URL, just not pasted into JavaScript as a string constant.

Related

Parse Complex Json String

I'm attempting to parse the following JSON string (not in control of the format, I know it's hideous).
var json = '{"what.1.does":"anything", "nestedjsonstr":"{\"whatup\":\"nada\"}"}';
obj = JSON.parse(json);
I'm getting Error: Unexpected token w in JSON at position 43 which is where the first value of nestedjsonstr begins. Is there any elegant way to parse this?
Maybe this can help you out. You replace the curly braces inside your string without the ", and remove the \.
var json = '{"what.1.does":"anything", "nestedjsonstr":"{\"whatup\":\"nada\"}"}';
json = json.replace('\"{', '{').replace('}\"', '}').replace('\\"', '"');
obj = JSON.parse(json);
console.log(obj);

Escape \51 in javascript

My issue is the following:
I have a field with a file path: "\\random.ad.test.stuff.com\folder\level 1\51. level 2\ level 3"
I want to create an array with this information
function myFunction() {
var str = "\\random.ad.test.stuff.com\folder\level 1\51. level 2\level 3";
var array = str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "_");
document.getElementById("demo").innerHTML = array;
}
Problem is that \51 the character code for a right parenthesis. So the result is
"_random_ad_test_stuff_comfolder_level 1__. level 2_level 3".
How can I escape the \51 as well as insert a _after .com ?
You can't escape the string after-the-fact. In a string literal, as you said, \51 is ), exactly as though you'd typed ) in the string literal; there is no difference in the resulting string:
console.log("\51" === ")"); // true
You have to escape the characters in the literal:
var str = "\\\\random.ad.test.stuff.com\\folder\\level 1\\51. level 2\\level 3";
// --------^-^-------------------------^-------^--------^------------^
console.log(str);
Note that this is just because you're using a string literal. If you read that string from somewhere, there's no need to escape it at all. Escaping (in this sense) is a string literal thing, not a string thing.
You've said this comes from an XML file, and asked what you have to do to the file to avoid this problem. The answer is: Nothing. Read in the XML file, and when you get those filenames from it, you'll get strings with the correct characters again, escaping is for string literals, but XML isn't a string literal.
Example:
// "Read" the file
var xmlText = document.querySelector("#xml").textContent;
// Parse it
var oParser = new DOMParser();
var oDOM = oParser.parseFromString(xmlText, "application/xml");
// Use its contents; the information you'll get will be valid strings,
// no escaping needed
var entries = oDOM.querySelectorAll("entry");
console.log(entries[0].getAttribute("attr"));
console.log(entries[1].firstChild.nodeValue);
<script id="xml" type="text/xml"><root>
<entry attr="\\random.ad.test.stuff.com\folder\level 1\51. level 2\level 3" />
<entry>\\random.ad.test.stuff.com\folder\level 1\51. level 2\level 3</entry>
</root></script>
In that example, I've shown taking the string from an attribute, or from the body of an element, the two usual ways you put information in XML.

Decoding not working with Base64

Encoding my URL works perfectly with base-64 encoding. So does decoding but not with the string literal variable.
This works:
document.write(atob("hi"));
This does not:
var tempvar = "hello";
document.write(atob(tempvar));
What am I doing wrong? Nothing is displayed. But if I quote "tempvar", then it of course works but is not the same thing since "tempvar" is a string, not a variable.
Your Question
What am I doing wrong?
The string being passed to atob() is a string literal of length 5 (and not technically a base-64 encoded string). The browser console should reveal an exception in the error log (see explanation in The cause below).
The cause
Per the MDN documentation of atob():
Throws
Throws a DOMException if the length of passed-in string is not a multiple of 4. 1
The length of the string literal "hello" (i.e. 5) is not a multiple of 4. Thus the exception is thrown instead of returning the decoded version of the string literal.
A Solution
One solution is to either use a string that has actually been encoded (e.g. with btoa()) or at least has a length of four (e.g. using String.prototype.substring()). See the snippet below for an example.
var tempvar = "hello";
window.addEventListener("DOMContentLoaded", function(readyEvent) {
var container = document.getElementById("container");
//encode the string
var encoded = btoa(tempvar);
container.innerHTML = encoded;
var container2 = document.getElementById("container2");
//decode the encoded string
container2.innerHTML = atob(encoded);
var container3 = document.getElementById("container3");
//decode the first 4 characters of the string
container3.innerHTML = atob(tempvar.substring(0, 4));
});
<div> btoa(tempvar): <span id="container"></span></div>
<div> atob(decoded): <span id="container2"></span></div>
<div> atob(tempvar.substring(0, 4)): <span id="container3"></span></div>
1https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/atob
It's because it can't decode the string "hello", try an actual string that can be decoded from base64, here is an example;
var tempvar = "aHR0cDovL3N0YWNrb3ZlcmZsb3cuY29tL3F1ZXN0aW9ucy80MzEyOTEzNi9kZWNvZGluZy1ub3Qtd29ya2luZy13aXRoLWJhc2U2NA==";
document.write(atob(tempvar));
If you want to encode, use the btoa function instead,
var tempvar = "hello";
document.write(btoa(tempvar));
You can use this website to test decoding and encoding base64, https://www.base64encode.org/
it's because you are trying to decode a not base64 encoded string
that it works on hi is just a coincidence it seems.
atob = decode
btoa = encode
You're using the wrong function. You should use btoa() to encode.
When you do atob('hi'), you're actually decoding 'hi', which happens to be valid base-64.

Javascript convert windows-1252 encoding to UTF-8

How do I convert the below string:
var string = "Bouchard+P%E8re+et+Fils"
using javascript into UTF-8, so that %E8 would become %C3%A8?
Reason is this character seems to be tripping up decodeURIComponent
You can test it out by dropping the string into http://meyerweb.com/eric/tools/dencoder/ and seeing the console error that says Uncaught URIError: URI malformed
I'm looking specifically for something that can decode an entire html document, that claims to be windows-1252 encoded which is where I assume this %E8 character is coming from, into UTF-8.
Thanks!
First create a map of Windows-1252. You can find references to the encoding using your search engine of choice.
For the sake of this example, I'm going to include on the character in your sample data.
Then find all the percentage signs followed by two hexadecimal characters, convert them to numbers, and convert them using the map (to get raw data), then convert them again using encodeURIComponent (to get the encoded data).
var string = "Bouchard+P%E8re+et+Fils"
var w2512chars = [];
w2512chars[232] = "รจ"
var percent_encoded = /(%[a-fA-F0-9]{2})/g;
function filter(match, group) {
var number = parseInt(group.substr(1), 16);
var character = w2512chars[number];
return encodeURIComponent(character);
}
string = string.replace(percent_encoded, filter);
alert(string);

JavaScript - Parsing JSON with carriage and new line spaces

I am using the following JS code to parse a JSON string from a separate JS file:
// extract JSON from a module's JS
var jsonMatch = data.match( /\/\*JSON\[\*\/([\s\S]*?)\/\*\]JSON\*\// );
data = JSON.parse( jsonMatch ? jsonMatch[1] : data );
This is an example of the JS file I extract the JSON string from:
JsonString = /*JSON[*/{"entities":[{"type":"EntityPlayer","x":88,"y":138}]}/*]JSON*/;
This code works just fine, however if the JS file with the JSON string contains carriage returns and isn't on one complete line then I get a syntax error.
Example:
JsonString = /*JSON[*/{
"entities":[{
"type":"EntityPlayer",
"x":88,
"y":138}]
}/*]JSON*/;
Returns the following error:
JSON.parse: unexpected non-whitespace character after JSON data
Any idea how I could modify my parsing to work by either stripping out whitespace or to remove carriage returns and new line spaces?
data = JSON.parse( (jsonMatch ? jsonMatch[1] : data).replace(/\n/g,"") );
Did not test it, but maybe this is what you are looking for?
var JsonString = JsonString.replace(new RegExp( "\\n", "g" ),"");
(from http://www.bennadel.com/blog/161-Ask-Ben-Javascript-Replace-And-Multiple-Lines-Line-Breaks.htm)

Categories