What is arbitrary data/JSON? - javascript

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).

Related

Is there any generic function for subscripting?

I have a web page in which contents are loaded dynamically from json. Now i need to find the texts like so2,co2,h2o after the page gets loaded and have to apply subscript for those texts. Is it possible to do this?? If yes please let me know the more efficient way of achieving it.
for example :
var json = { chemA: "value of CO2 is", chemB: "value of H2O is" , chemC: "value in CTUe is"};
in the above json i need to change CO2,H2O and e in CTUe as subscript. how to achieve this??
Take a look at this JSfiddle which shows two approaches:
HTML-based using the <sub> tag
Pure Javascript-based by replacing the matched number with the subscript equivalent in unicode:
http://jsfiddle.net/7gzbjxz3/
var json = { chemA: "CO2", chemB: "H2O" };
var jsonTxt = JSON.stringify(json).replace(/(\d)+/g, function (x){
return String.fromCharCode(8320 + parseInt(x));
});
Option 2 has the advantage of being more portable since you're actually replacing the character. I.e., you can copy and paste the text into say notepad and still see the subscripts there.
The JSFiddle shows both approaches. Not sure why the magic number is 8320 when I was expecting it to be 2080...
So you are generating DOM element as per JSON data you are getting. So before displaying it to DOM you can check if that JSON data contains so2,co2,h2o and if it is then replace that with <sub> tag.
For ex:
var text = 'CO2';
text.replace(/(\d+)/g, "<sub>" + "$1" + "</sub>") ;
And this will returns something like this: "CO2".
As per JSON provided by you:
// Only working for integer right now
var json = { chemA: "value of CO2 is", chemB: "value of H2O is" , chemC: "value in CTUe is"};
$.each(json, function(index, value) {
json[index] = value.replace(/(\d+)/g, "<sub>" + "$1" + "</sub>");
});
console.log(json);
Hope this will helps!
To do this, I would create a prototype function extending String and name it .toSub(). Then, when you create your html from your json, call .toSub() on any value that might contain text that should be in subscript:
// here is the main function
String.prototype.toSub = function() {
var str=this;
var subs = [
['CO2','CO<sub>2</sub>'],
['H2O','H<sub>2O</sub>'],
['CTUe','CO<sub>e</sub>'] // add more here as needed.
];
for(var i=0;i<subs.length;i++){
var chk = subs[i][0];
var rep = subs[i][1];
var pattern = new RegExp('^'+chk+'([ .?!])|( )'+chk+'([ .?!])|( )'+chk+'[ .?!]?$','ig'); // makes a regex like this: /^CO2([ .?!])|( )CO2([ .?!])|( )CO2[ .?!]?$/gi using the surrent sub
// the "empty" capture groups above may seem pointless but they are not
// they allow you to capture the spaces easily so you dont have to deal with them some other way
rep = '$2$4'+rep+'$1$3'; // the $1 etc here are accessing the capture groups from the regex above
str = str.replace(pattern,rep);
}
return str;
};
// below is just for the demo
var json = { chemA: "value of CO2 is", chemB: "value of H2O is" , chemC: "value in CTUe is", chemD: "CO2 is awesome", chemE: "I like H2O!", chemF: "what is H2O?", chemG: "I have H2O. Do you?"};
$.each(json, function(k, v) {
$('#result').append('Key '+k+' = '+v.toSub()+'<br>');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="result"></div>
Note:
Anytime you do something like this with regex, you run the chance of unintentionally matching and converting some unwanted bit of text. However, this approach will have far fewer edge cases than searching and replacing text in your whole document as it is much more targeted.

jquery iteration of xml response

I have xml respnse from ajax call. I want to iterate it.
Below is my xml ouput in SoaUi.
I want output response as below:
50 Water St Oakland USA
101 Emerall New York USA
Sea Point CA USA
Please help me to write response in jQuery.
EDIT:
This is my response in xml:
<ns3:Row>
<ns3:AddressLine1>50 Water St</ns3:AddressLine1>
<ns3:City>Oakland</ns3:City>
<ns3:Country>USA</ns3:Country>
</ns3:Row>
<ns3:Row>
<ns3:AddressLine1>101 Emerall</ns3:AddressLine1>
<ns3:City>New York</ns3:City>
<ns3:Country>USA</ns3:Country>
</ns3:Row>
<ns3:Row>
<ns3:AddressLine1>Sea Point</ns3:AddressLine1>
<ns3:City>CA</ns3:City>
<ns3:Country>USA</ns3:Country>
</ns3:Row>
You can get the information required looping through the elements and storing the information in a string or whatever you find fit.
One solution (mixing jquery and plain javascript) could be as follows:
$(f).each(function (ind, el) {
var line = '';
$(el).children().each(function (ind, nod) {
line += nod.childNodes[0].nodeValue + ' ';
});
console.log(line.slice(0, -1));
});
the variable 'f' contains the XML string retrieved from the server.
You can test it in this fiddle (open the developer's console to see the result printed there).
Hope it helps.
Solution is here.
var geoCompAddress;
$(data).find('ns3\\:Row').each(function() {
geoCompAddress = $(this).find('ns3\\:AddressLine1').text()+ ',' + $(this).find('ns3\\:City').text()+ ',' + $(this).find('ns3\\:Country').text() ;
});

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"]]()

ExtJs 4 - Convert JS object to xml

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;
}

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.

Categories

Resources