ExtJs 4 - Convert JS object to xml - javascript

Im using ExtJs 4.2.1.
Is there an "easy" way to convert JS object to xml? I mean a simple function like:
Ext.JSON.encode(object);
To convert object to Json.
Lets say the following object for example:
Root:
Child1
Child2
Child3
To the following xml:
<Root>
<Child1> some value </Child1>
<Child2> some value </Child2>
<Child3> some value </Child3>
</Root>
I was trying to search it in the documentation, but didn't came to any solution like that.
Thanks.

make a XML string using Json data and convert the XML string to XML object
To convert string to XML go through the following link
How to convert string to XML object in JavaScript?

Eventually I used this nice script for the conversion.
Hopefully Sencha will add built in functions for encoding xml in future versions.

One easy way to do it is using a middle tier Java class. Lot of java libraries available to convert JSON to XML like Jackson, eclipsemoxy

I did wrote one method while using EXT JS 4, i got the same problem for conversion of Javascript object to XML. this one handles Array Objects also. i have only considered my special cases non other.. so feel free to make any changes..
convertJsToXML: function (rec, rootNode) {
var xmlString = "";
var withoutRoot = false;
for (var object in rec) {
if (!isNaN(object)) {
withoutRoot = true;
xmlString += this.convertJsToXML(rec[object], rootNode);
} else if (typeof rec[object] == 'object') {
xmlString += this.convertJsToXML(rec[object], object);
} else if (rec[object] != null && rec[object] != "") {
xmlString += "<" + object + ">" + rec[object] + "</" + object + ">";
}
}
if (!withoutRoot)
xmlString = "<" + rootNode + ">" + xmlString + "</" + rootNode + ">";
return xmlString;
}

Related

Building JavaScript Array in C#, apostrophes changing

I have done this to build JavaScript Arrays from int, double and string lists.
public string listToJsArray<T>(List<T> cslist)
{
bool numeric = true;
if(
!(typeof(T)==typeof(int)
|| typeof(T) == typeof(string)
|| typeof(T) == typeof(double))
)
{
throw (new ArgumentException(message: "Only int, double and string are supported"));
}
if(typeof(T)==typeof(string))
{
numeric = false;
}
string JsArray = "[";
for(int i=0;i<cslist.Count;i++)
{
string dataWithSurrendings = cslist[i].ToString();
if(!numeric)
{
dataWithSurrendings = "'" + cslist[i].ToString() + "'";
}
if(i !=0)
{
dataWithSurrendings = "," + dataWithSurrendings;
}
if(i +1==cslist.Count)
{
dataWithSurrendings = dataWithSurrendings + "]";
}
JsArray += dataWithSurrendings;
}
return JsArray;
}
My problem is when a list of strings is passed, apostrophes turn into '.
for example, a list of {"1","2","3","4","5","6","7"} becomes this:
['1','2','3','4','1','6','7']
What modification is needed in this function, to return a correct array in JavaScript?
None of solutions did solve the problem. With JsonConvert I get almost same result. The problem is the single or double quote in View editor have not the same encoding as CS string.
I'm assuming that you are doing this to drop into a webpage somewhere, something like:
<script>
#{
var output = listToJsArray(Model.SomeList);
}
var myArray = #Html.Raw(output);
// some Javascript using that array
</script>
Don't waste your time trying to do it yourself. It's a pain and you are reinventing the wheel. JSON is valid Javascript and a serialization of an array into JSON is absolutely identical to a Javascript array literal. So use Javascript. JSON.Net is really useful here:
<script>
#{
var output = Newtonsoft.Json.JsonConvert.SerializeObject(Model.SomeList);
}
var myArray = #Html.Raw(output);
// some Javascript using that array
</script>
The serializer will handle all the annoying escaping, special characters and edge cases for you.

Replace array-mapped variables with the actual variable name/string?

I am trying to edit a Greasemonkey/jQuery script. I can't post the link here.
The code is obfuscated and compressed with minify.
It starts like this:
var _0x21e9 = ["\x67\x65\x74\x4D\x6F\x6E\x74\x68", "\x67\x65\x74\x55\x54\x43\x44\x61\x74\x65", ...
After "decoding" it, I got this:
var _0x21e9=["getMonth","getUTCDate","getFullYear", ...
It is a huge list (500+ ). Then, it has some variables like this:
month = date[_0x21e9[0]](), day = date[_0x21e9[1]](), ...
_0x21e9[0] is getMonth, _0x21e9[1] is getUTCDate, etc.
Is it possible to replace the square brackets with the actual variable name? How?
I have little knowledge in javascript/jQuery and can not "read" the code the way it is right now.
I just want to use some functions from this huge script and remove the others I do not need.
Update: I tried using jsbeautifier.org as suggested here and in the duplicated question but nothing changed, except the "indent".
It did not replace the array variables with the decoded names.
For example:
jsbeautifier still gives: month = date[_0x21e9[0]]().
But I need: month = date["getMonth"]().
None of the online deobfuscators seem to do this, How can I?
Is there a way for me to share the code with someone, at least part of it? I read I can not post pastebin, or similar here. I can not post it the full code here.
Here is another part of the code:
$(_0x21e9[8] + vid)[_0x21e9[18]]();
[8] is "." and [18] is "remove". Manually replacing it gives a strange result.
I haven't seen any online deobfuscator that does this yet, but the principle is simple.
Construct a text filter that parses the "key" array and then replaces each instance that that array is referenced, with the appropriate array value.
For example, suppose you have a file, evil.js that looks like this (AFTER you have run it though jsbeautifier.org with the Detect packers and obfuscators? and the Unescape printable chars... options set):
var _0xf17f = ["(", ")", 'div', "createElement", "id", "log", "console"];
var _0x41dcx3 = eval(_0xf17f[0] + '{id: 3}' + _0xf17f[1]);
var _0x41dcx4 = document[_0xf17f[3]](_0xf17f[2]);
var _0x41dcx5 = _0x41dcx3[_0xf17f[4]];
window[_0xf17f[6]][_0xf17f[5]](_0x41dcx5);
In that case, the "key" variable would be _0xf17f and the "key" array would be ["(", ")", ...].
The filter process would look like this:
Extract the key name using text processing on the js file. Result: _0xf17f
Extract the string src of the key array. Result:
keyArrayStr = '["(", ")", \'div\', "createElement", "id", "log", "console"]';
In javascript, we can then use .replace() to parse the rest of the JS src. Like so:
var keyArrayStr = '["(", ")", \'div\', "createElement", "id", "log", "console"]';
var restOfSrc = "var _0x41dcx3 = eval(_0xf17f[0] + '{id: 3}' + _0xf17f[1]);\n"
+ "var _0x41dcx4 = document[_0xf17f[3]](_0xf17f[2]);\n"
+ "var _0x41dcx5 = _0x41dcx3[_0xf17f[4]];\n"
+ "window[_0xf17f[6]][_0xf17f[5]](_0x41dcx5);\n"
;
var keyArray = eval (keyArrayStr);
//-- Note that `_0xf17f` is the key name we already determined.
var keyRegExp = /_0xf17f\s*\[\s*(\d+)\s*\]/g;
var deObsTxt = restOfSrc.replace (keyRegExp, function (matchStr, p1Str) {
return '"' + keyArray[ parseInt(p1Str, 10) ] + '"';
} );
console.log (deObsTxt);
if you run that code, you get:
var _0x41dcx3 = eval("(" + '{id: 3}' + ")");
var _0x41dcx4 = document["createElement"]("div");
var _0x41dcx5 = _0x41dcx3["id"];
window["console"]["log"](_0x41dcx5);
-- which is a bit easier to read/understand.
I've also created an online page that takes JS source and does all 3 remapping steps in a slightly more automated and robust manner. You can see it at:
jsbin.com/hazevo
(Note that that tool expects the source to start with the "key" variable declaration, like your code samples do)
#Brock Adams solution is brilliant, but there is a small bug: it doesn't take into account simple quoted vars.
Example:
var _0xbd34 = ["hello ", '"my" world'];
(function($) {
alert(_0xbd34[0] + _0xbd34[1])
});
If you try to decipher this example, it will result on this:
alert("hello " + ""my" world")
To resolve this, just edit the replacedSrc.replace into #Brock code:
replacedSrc = replacedSrc.replace (nameRegex, function (matchStr, p1Str) {
var quote = keyArry[parseInt (p1Str, 10)].indexOf('"')==-1? '"' : "'";
return quote + keyArry[ parseInt (p1Str, 10) ] + quote;
} );
Here you have a patched version.
for (var i = 0; i < _0x21e9.length; i++) {
var funcName = _0x21e9[i];
_0x21e9[funcName] = funcName;
}
this will add all the function names as keys to the array. allowing you to do
date[_0x21e9["getMonth"]]()

convert html into javascript string

I'm getting some html from node-request and I want to place that html into my javascript code as strings:
<div id='frontpage'><div set-href="'/user/' + (user | encodeURIComponent)">userlink</div></div>
The goal is to get an output like this for angularjs:
var createCache = function (path, template) {
return "\n $templateCache.put('" + path + "',\n '" +template + "'\n );\n";
}
This code is too naive, there are issues with quotes and other potential problems. How could it be done correctly? Is there a way to get the string from node-request itself? Thanks.

What is arbitrary data/JSON?

I've recently come across the term arbitrary data/ arbitrary json and i can't seem to understand what exactly is it and/or find any documentation on it. I know that JSON is a format for sending data over the internet, so how exactly can a format be arbitrary?
EDIT::
//more code
var buildItem = function(item) {
var title = item.name,
args = [],
output = '<li>';
if (item.type == 'method' || !item.type) {
if (item.signatures[0].params) {
$.each(item.signatures[0].params, function(index, val) {
args.push(val.name);
});
}
title = (/^jQuery|deferred/).test(title) ? title : '.' + title;
title += '(' + args.join(', ') + ')';
} else if (item.type == 'selector') {
title += ' selector';
}
output += '<h3>' + title + '</h3>';
output += '<div>' + item.desc + '</div>';
output += '</li>';
return output;
};
//more code
in the example code above, i am told that the .params is arbitrary data from a JSON request [for the jQuery API documentation].
What then is arbitrary data?
Would really appreciate any answers and/or clarifications.
jsFiddle: http://jsfiddle.net/QPR4Z/2/
Thanks!
arbitrary |ˈärbiˌtrerē|
adjective
based on random choice or personal whim, rather than any reason or
system: his mealtimes were entirely arbitrary.
Mathematics: (of a constant or other quantity) of unspecified value.
It just means there could be any value in there. This is opposed to a specification that says something like "this array always contains X, Y and Z". Arbitrary values in contrast say "we're sending you something in this array, but we can't really tell you in advance what exactly that is." If you're told that you can send arbitrary data yourself, it means you can send anything you want, it doesn't have to follow any particular format.
Note that this is all about the data contained in the JSON format, not about the JSON format itself.
It means "Some organisation of the data structure (including names of properties) that was just made up by some person" rather than being an established standard.
The data structure is arbitrary. It is expressed in the JSON standard (which isn't).

Dojo Toolkit: how to escape an HTML string?

A user of my HTML 5 application can enter his name in a form, and this name will be displayed elsewhere. More specifically, it will become the innerHTML of some HTML element.
The problem is that this can be exploited if one enters valid HTML markup in the form, i.e. some sort of HTML injection, if you will.
The user's name is only stored and displayed on the client side so in the end the user himself is the only one who is affected, but it's still sloppy.
Is there a way to escape a string before I put it in an elements innerHTML in Dojo? I guess that Dojo at one point did in fact have such a function (dojo.string.escape()) but it doesn't exist in version 1.7.
Thanks.
dojox.html.entities.encode(myString);
Dojo has the module dojox/html/entities for HTML escaping. Unfortunately, the official documentation still provides only pre-1.7, non-AMD example.
Here is an example how to use that module with AMD:
var str = "<strong>some text</strong>"
require(['dojox/html/entities'], function(entities) {
var escaped = entities.encode(str)
console.log(escaped)
})
Output:
<strong>some text</strong>
As of Dojo 1.10, the escape function is still part of the string module.
http://dojotoolkit.org/api/?qs=1.10/dojo/string
Here's how you can use it as a simple template system.
require([
'dojo/string'
], function(
string
){
var template = '<h1>${title}</h1>';
var message = {title: 'Hello World!<script>alert("Doing something naughty here...")</script>'}
var html = string.substitute(
template
, message
, string.escape
);
});
I tried to find out how other libraries implement this function and I stole the idea of the following from MooTools:
var property = (document.createElement('div').textContent == null) ? 'innerText': 'textContent';
elem[property] = "<" + "script" + ">" + "alert('a');" + "</" + "script" + ">";
So according to MooTools there is either the innerText or the textContent property which can escape HTML.
Check this example of dojo.replace:
require(["dojo/_base/lang"], function(lang){
function safeReplace(tmpl, dict){
// convert dict to a function, if needed
var fn = lang.isFunction(dict) ? dict : function(_, name){
return lang.getObject(name, false, dict);
};
// perform the substitution
return lang.replace(tmpl, function(_, name){
if(name.charAt(0) == '!'){
// no escaping
return fn(_, name.slice(1));
}
// escape
return fn(_, name).
replace(/&/g, "&").
replace(/</g, "<").
replace(/>/g, ">").
replace(/"/g, """);
});
}
// that is how we use it:
var output = safeReplace("<div>{0}</div",
["<script>alert('Let\' break stuff!');</script>"]
);
});
Source: http://dojotoolkit.org/reference-guide/1.7/dojo/replace.html#escaping-substitutions

Categories

Resources