Javascript: SHA512 value convert to JSON object - javascript

I already crypt the variable 'getShaValue' to sha512. Then combine it with many variable like 'name','ic' using JSON.stringify. But when I debug my JSON object, the value of SHA512 didn't show the right value. If I only debug the value before convert it into JSON, it show the right value.
Here is my function to crypt the value
self.sha512 = function () {
var value = self.generateSHAvalue();
var getShaValue= CryptoJS.SHA512(value);
return getShaValue;
};
I combine it with many variable
var authToken = SHA.sha512();
var requestData = JSON.stringify({
name: "Test",
authToken: authToken
})
console.log("requestData: " + JSON.stringify(requestData));
The result of the console is
{
"name": "Test",
"authToken": '"$super":{"$super":{}},"words":[1157899753,2720090447,1588426441,2244605341,2288345873,3771352114,2976397435,3171064119,-130018106,2601059156,3822838925,2519334849,1988499628,2785343384,-556559616,-1270654637],"sigBytes":64'
}
But it should be like this:
{
"name": "Test",
"authToken": "21507C7061D3F45058A95751E2FB332DD68F6A2ADC2039DE4341199643E12ADEFB8DF603C3F 34E71FB447F46B82BC5DC7BD2B81B83B389D8950583BEFB424676"
}
Can anyone help me. Thanks.

You included the binary digest in the json. Try converting it to hex first:
self.sha512 = function () {
var value = self.generateSHAvalue();
var shaHex = CryptoJS.SHA512(value).toString(CryptoJS.enc.Hex);
return shaHex ;
};

Related

Setting application/json as the data during the dragstart in HTML5 DND

I observed the setting the JSON data in HTML5DND will be converted into string. Are there any alternatives and best practices for passing JSON Data other than stringifying.
// During drag enter
event.dataTransfer.setData('application/json', {
id: 1
});
// During Drop data is printing as object
let data = event.dataTransfer.getData('application/json');
// printing [object Object]
There is no alternative for DataTransfer.setData() because its data (second) argument is a DOMString.
There is an alternative to DataTransfer--DataTransferItem; however, using it will involve stringifying the object (to pack that into a Blob of mimetype JSON).
In case my other answer does not answer your question, try dragging/dropping the object avatars into the textarea.
const object_1 = {id: 1}
const object_2 = {id: 2}
const p_1 = document.body.appendChild(document.createElement("p"))
const p_2 = document.body.appendChild(document.createElement("p"))
p_1.innerText = "object_1"
p_1.draggable = true
p_2.innerText = "object_2"
p_2.draggable = true
p_1.ondragstart = function () {
event.dataTransfer.setData("text", "object_1")
}
p_2.ondragstart = function () {
event.dataTransfer.setData("text", "object_2")
}
const textarea = document.body.appendChild(document.createElement("textarea"))
textarea.ondrop = function() {
event.preventDefault()
this.innerText = eval(event.dataTransfer.getData("text")).id
}

Looking for eval() alternative when node/attribute name is variable/parameter

It is clear that when the attribute (for example id) exists/is defined in the script, we should use obj[id] and not eval('obj.' + id). However, I have not yet found a solution for the case where the attribute name is itself a variable and not defined - for example when recieved as a parameter. In my case I have node.js on the server recieving a JSON object requestData being sent from the client via socket.io. The requestData contains a key/value pair: requestData.key is an array of the node names that make up the JSON path to the element, and requestData.val is the value to be stored in that element.
In the server script there is a defined JSON object called root which contains information relevant to the app, for example:
"root": {
"pages": {
"TM1010": {
"appId": "TM1010",
"componentName": "UserTasksPage"
},
"TM1020": {
"appId": "TM1020",
"componentName": "UsersPage"
}
}
}
If the client were to send a request to update an element - for example to change the value of root.pages.TM1010.componentName - this is how it would be sent from the client:
let requestData = {'key': ['pages', 'TM1010', 'componentName'], 'val': newComponentName};
this.socket.emit('changeData', requestData);
And this is how it is recieved and executed on the server:
socket.on('changeData', (requestData) => {
var str = 'root'
var key = requestData.key
var len = key.length;
for (var i = 0; i < len; i++) {
str = str + '["' + key[i] + '"]'
}
str = str + '=requestData.val'
eval(str)
});
So that what is being executed in the end (the value of str) is:
root["pages"]["TM1010"]["componentName"]=requestData.val
How could this be done without eval() ?
As I mentioned, I do not know the names of those elements that will be sent from the client. All I have on the server is one JSON object called 'root' and I want to continuously add/update to it as I recieve data from the client.
I have tried solutions based on JEXL or mathjs but it doesn't seem to work for this type of case.
You could reduce the keys by taking the object and assign the value with the last key.
const
setValue = (object, keys, value) => {
var path = keys.slice(),
last = path.pop();
path.reduce((o, k) => o[k], object)[last] = value;
};
var data = { root: { pages: { TM1010: { appId: "TM1010", componentName: "UserTasksPage" }, TM1020: { appId: "TM1020", componentName: "UsersPage" } } } },
requestData = { key: ['pages', 'TM1010', 'componentName'], val: 'newComponentName' };
setValue(data.root, requestData.key, requestData.val);
console.log(data);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Get value from Request URL response data

Requested URL sent - https://www.example.com/detail.guest.html?ppc=FDE466920006DCEFA697BF982FC9C87C5B257ECB2230CBF4D6D6CA740C7B894D5795F70DED928ED3B00C1F3F77DF974DFD73882DEBDD7EC063B37DEB24CF655528FD911109C57961AE314C612772AADFD2E193D572E6F6C8E249A6DAA
Get below response data correctly as expected by 3rd party.
BookersID=250100000002;BookersTitle=Mr;BookersFirstName=test1;BookersLastName=test2
I want to extract "BookersID", "BookersTitle", "BookersFirstName", "BookersLastName" separately and display this value in input field.
JS:
var bookerID = data[0].BookersID;
var bookerTitle = data[0].BookersTitle;
var bookerFname = data[0].BookersFirstName;
var bookerLname = data[0].BookersLastName;
console.log("BookersID", bookerID);
console.log("BookersTitle", bookerTitle);
But getting error in display value.
Please let me know how to get the value in console log?
Thanks
First you need to get data from your xhr request. To do that you need to add callback function. (More info in jQuery.get() documentation)
$.get( endpoint, function( data ) { // add callback to handle response
// ... parse data here
});
As I understand you need to parse data. It could be done by using String.prototype.split method and simple mapping.
console.log(data) // BookersID=250100000002;BookersTitle=Mr;BookersFirstName=test1;BookersLastName=test2
var parsed = data.split(';').map(part => ({ name: part.split('=')[0], value: part.split('=')[1] }));
console.log(parsed);
Output:
[
{name: "BookersID", value: "250100000002"},
{name: "BookersTitle", value: "Mr"},
{name: "BookersFirstName", value: "test1"},
{name: "BookersLastName", value: "test2"}
]
If you want to get data as an object:
var parsedObject = parsed.reduce(
(obj, item) => Object.assign(obj, {[item.name]: item.value}) ,{});
// {BookersID: "250100000002", BookersTitle: "Mr", BookersFirstName: "test1", BookersLastName: "test2"}
If you getting the same response you need to write a utility function to convert the same into an object
function _convert(responseString) {
var _obj = {};
responseString.split(";").forEach(function(pair){
var _pairArr = pair.split("=");
_obj[_pairArr[0]] = _pairArr[1];
});
reuturn _obj;
}
var responseString = "BookersID=250100000002;BookersTitle=Mr;BookersFirstName=test1;BookersLastName=test2";
var obj = _convert(responseString);
obj['BookersID']; // 250100000002
// or
obj.BookersID; // 250100000002
Note: This will only work if your response has exactly the same format as you have mentioned.
var str = 'BookersID=250100000002;BookersTitle=Mr;BookersFirstName=test1;BookersLastName=test2';
var data = {};
var parsed = str.split(';').map(part => { let x = part.split("="); data[x[0]] = x[1]; console.log(x) });
console.log(data)
Output:
{BookersID: "250100000002", BookersTitle: "Mr", BookersFirstName: "test1", BookersLastName: "test2"}
You could use .reduce() and .split() to create your string into an object, which can then have its properties accessed
const data = "BookersID=250100000002;BookersTitle=Mr;BookersFirstName=test1;BookersLastName=test2";
const dataObj = data.split(';').reduce((acc, kvp) =>
({
...acc,
...(([key, value]) => ({[key]: value}))(kvp.split('='))
}), {});
console.log(dataObj);
// access properties:
console.log(dataObj.BookersID);

How to insert data in json after crawling through casperjs?

I wrote code that parsing a lot of words (innerHTML) from some webpages.
and I'd like to insert data to json file directly..
Here is my js code...
var words = [];
var casper = require('casper').create();
function getWords() {
var words = document.querySelectorAll('td.subject a');
return Array.prototype.map.call(words, function(e) {
return e.innerHTML;
});
}
casper.start('http://www.todayhumor.co.kr/board/list.php?table=bestofbest', function() {
words = this.evaluate(getWords);
});
for (var i=2; i <=5; i++) {
casper.thenOpen('http://www.todayhumor.co.kr/board/list.php?table=bestofbest&page='+i, function() {
words = words.concat(this.evaluate(getWords));
});
}
casper.run(function() {
// echo results in some pretty fashion
this.echo(words.length + ' links found:').exit();
this.echo(words.join('\n')).exit();
});
and
I run this code through terminal like this!
username#wow:~/workspace/app/assets/javascripts $ casperjs application.js
and the result is (for example)
150 words found:
apple
banana
melon
kiwi
citrus
watermelon
passionfruit
mango
orange
...
So I want to insert this data in "word" part of my json file (example code of json below)
and make other columns("type": "fruit" and "spell":) automatically added
{ "my_initial_words": [
{
"type": "fruit",
"word": "apple",
"spell": "ap"
},
{
"type": "fruit",
"word": "banana",
"spell": "ba"
},
{
"type": "fruit",
"word": "melon",
"spell": "me"
}
]
}
----------------------------------------------------------------------------
thanks for adding more answer!..
but I couldn't catch where should I put these code
Could you tell me once more that... Which code you gave me executes "Saving the results to JSON file?" because I have to read json file(makeyourap.json) in my seeds.rb file like this
require 'json'
file = File.open(Rails.root.join('db','makeyourap.json'))
contents = file.read
json = ActiveSupport::JSON.decode(contents)["my_initial_words"]
So, something like this?
function makeTypeObject(name, type) {
return {
name: name,
type: type,
spell: name.substr(0,2)
};
}
var wordDesc = words.map(function (word) {
return makeTypeObject(word, "fruit");
});
var finalObject = {
my_initial_words: wordDesc
};
var jsonString = JSON.stringify(finalObject);
// if you want prettyprint, try JSON.stringify(finalObject, null, "\t");
I hope this helps.
Write to file via casper
If you want to have a file from which you read and write, appending content, you can do it like this:
var fs = require('fs');
var FILENAME = 'makeyourap.json';
function add_new_fruits(fruits) {
var data;
if ( fs.isFile(FILENAME) ) {
data = fs.read(FILENAME);
} else {
data = JSON.stringify({'my_initial_words' : [] });
}
var json = JSON.parse(data);
fruits.forEach(function(word) {
json.my_initial_words.push({"type": "fruit",
"name": word,
"spell": word.slice(0,2)});
});
data = JSON.stringify(json, null, '\t');
fs.write(FILENAME, data, "w");
}
Use this instead of the older this.echo. Just call it as
casperjs application.js
This either reads the object from a file, or creates it if it does not exist. Then, it appends each new object from the new fruits (including duplicates), and writes it back to FILENAME.
Previous approach: how to roll your own
create Object
So first, you want to create an object that only has the parameter my_initial_words with values as above.
You can create a function via
function createFinal(wordArray) {
var out = [];
wordArray.forEach(function(word) {
out.push({"type": "fruit", "name": word, "spell": word.slice(0,2)});
});
return out;
}
to create the array. Then, create the object via
var my_object = { "my_initial_words": createFinal(words) };
to JSON
Javascript has a built-in JSON-object. With a javascript-object like
var my_object = { "my_initial_words": ...
as above, use
JSON.stringify(my_object)
to get the JSON representation to write.
Older: write to file via redirection
Before, you had
this.echo(words.join('\n')).exit();
which gave you the basic list. Using this.echo, try replacing this by
var my_object = { "my_initial_words": createFinal(words) };
this.echo(JSON.stringify(my_object)).exit();
This prints to standard output. Just remove the other this.echo line (150 words found) and redirect the output via
casperjs application.js > makeyourap.json
If you want to write to file in casperjs, look at write-results-into-a-file-using-casperjs.

Using openexchangerates API for currency conversion using JS/JQuery

I have managed to place JSON data into a form-control using JS which is this:
$("#getRates").ready(function () {
$.getJSON("http://openexchangerates.org/api/currencies.json?app_id="APP_ID", function (data) {
console.log(data);
for (var value in data) {
if (data.hasOwnProperty(value)) {
var text = document.createTextNode(value);
var select = document.getElementsByClassName('form-control')[1];
select.appendChild(document.createElement('option')).appendChild(text);
}
}
The current JSON file only contains the countries names but I wish to use the a different JSON file which is called Latest.JSON and contains the most recent rates, but it has these fields:
"license":
"timestamp": 1417258840,
"base": "USD",
"rates": {
"AED": 3.672743,
"AFN": 57.800375,
How can I just use the append the "rates" to the form-function and use the rates for the conversion?
As I have previously tried I just console.log and receive "License" "timestamp" "base" but no rates?
Not after specific answer maybe just some direction towards where to look?
$.getJSON("http://openexchangerates.org/api/latest.json?app_id=b65b6f0a06204a6087bab9a63a5845b7", function (data) {
console.log(data.rates);
for (var key in data.rates) {
if (data.rates.hasOwnProperty(key)) {
var text = document.createTextNode(key);
var select = document.getElementsByClassName('form-control')[1];
console.log(select);
select.appendChild(document.createElement('option')).appendChild(text);
}
}
for (var value in data.rates) {
if (data.rates.hasOwnProperty(value)) {
var text = document.createTextNode(value);
var select = document.getElementsByClassName('form-control')[2];
console.log(select);
select.appendChild(document.createElement('option')).appendChild(text);
}
}
});
});
I changed the var key to data.rates and this seems to of solved it.
This now populates both of my form-cotrols with the data.rates values from latest.json ..
The console.log() is just for my own usage..

Categories