Javascript from Buffer to JSON - javascript

I'm using bleno (A node js BLE package) and it uses Buffer to send and receive data. How will I go about getting a Buffer object and converting it into JSON? This is what i have now:
bufferToJson = buffer.toString();
bufferToJson = JSON.stringify(bufferToJson)
bufferToJson = JSON.parse(bufferToJson)
buffer is where the data is. An example of what buffer can be is {cmd:'echo'} I have tried bufferToJson.cmd and only get undefine. Thanks.

If your buffer object contains a valid representation of a JSON, then the easiest way to convert it would be like so:
const json = JSON.parse(buffer);

Following should work:
var bufferToJson = JSON.parse(myBuffer.toString());

You can use TextDecoder as in following fragment:
const buffer = await characteristic.readValue();
const decoder = new TextDecoder('utf8');
const text = decoder.decode(buffer);
console.log(JSON.parse(text));

For nodejs apps, I found String Decoder to work out great.
https://nodejs.org/api/string_decoder.html
// API for decoding Buffer objects into strings
const { StringDecoder } = require('string_decoder');
const decoder = new StringDecoder('utf8');
let body = Buffer.from(response.body);
let json = decoder.write(body);
let foo = JSON.parse(json);

Related

I am facing 401 with fiserv ucom all apis I do not know what is wrong with HMAC signature

I am trying to make HMAC signature in node js. I am doing properly as mentioned in the documentation. But not able to create the signature. Please find the code below,
let computedHash = CryptoJS.algo.HMAC.create(
CryptoJS.algo.SHA256,
key
);
computedHash.update(rawSignature);
computedHash = computedHash.finalize();
const computedHmac = CryptoJS.enc.Base64.stringify(computedHash);
Since the key and rawSignature are "base64 encoded" you need to "convert" them before using them
Perhaps this demonstration will help
const expectedOutput = btoa( "5bdcc146bf60754e6a042426089575c75a003f089d2739839dec58b964ec3843".replace(/../g, (hex) => String.fromCharCode(parseInt(hex, 16))));
console.log("Test vector result should be");
console.log(expectedOutput);
(() => {
// mock inputs as regular strings
const key = "Jefe"
const rawSignature = "what do ya want for nothing?"
// --- your code
let computedHash = CryptoJS.algo.HMAC.create(
CryptoJS.algo.SHA256,
key
);
computedHash.update(rawSignature);
computedHash = computedHash.finalize();
let computedHmac = CryptoJS.enc.Base64.stringify(computedHash);
console.log("inputs are strings");
console.log(computedHmac);
})();
(() => {
// mock inputs as base64 encoded strings
const key = btoa("Jefe");
const rawSignature = btoa("what do ya want for nothing?");
// --- your code
let computedHash = CryptoJS.algo.HMAC.create(
CryptoJS.algo.SHA256,
key
);
computedHash.update(rawSignature);
computedHash = computedHash.finalize();
computedHmac = CryptoJS.enc.Base64.stringify(computedHash);
console.log("inputs are base64 encoded - not decoding them where they are used");
console.log(computedHmac);
})();
(() => {
// mock inputs as base64 encoded strings
const key = btoa("Jefe");
const rawSignature = btoa("what do ya want for nothing?");
// --- your code
let computedHash = CryptoJS.algo.HMAC.create(
CryptoJS.algo.SHA256,
CryptoJS.enc.Utf8.stringify(CryptoJS.enc.Base64.parse(key))
);
computedHash.update(CryptoJS.enc.Utf8.stringify(CryptoJS.enc.Base64.parse(rawSignature)));
computedHash = computedHash.finalize();
computedHmac = CryptoJS.enc.Base64.stringify(computedHash);
console.log("inputs are base64 encoded - decoding them where they are used");
console.log(computedHmac);
})();
<script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/4.1.1/crypto-js.min.js"></script>

javascript - convert string to json array

I was using s3 select to fetch selective data and display them on my front end .
I converted array of byte to buffer and then to string like below as string
let dataString = Buffer.concat(records).toString('utf8');
the result i got was string like below
{"id":"1","obj1":"191.25","obj2":"11.81","obj3":"3.44","obj4":"15.62"}
{"id":"2","obj1":"642.00","obj2":"4.33","obj3":"0.00","obj4":"11.33"}
{"id":"3","obj1":"153.76","obj2":"94.77","obj3":"16.80","obj4":"29.79"}
{"id":"4","obj1":"61.71","obj2":"0.43","obj3":"0.00","obj4":"8.14"}
{"id":"5","obj1":"194.33","obj2":"108.89","obj3":"14.13","obj4":"168.60"}
{"id":"6","obj1":"204.31","obj2":"137.41","obj3":"34.76","obj4":"193.16"}
{"id":"7","obj1":"199.53","obj2":"34.53","obj3":"16.29","obj4":"26.56"}
{"id":"8","obj1":"77.33","obj2":"5.00","obj3":"12.50","obj4":"0.00"}
{"id":"9","obj1":"128.54","obj2":"101.60","obj3":"15.76","obj4":"46.23"}
{"id":"10","obj1":"107.00","obj2":"116.67","obj3":"34.42","obj4":"8.75"}
{"id":"12","obj1":"206.05","obj2":"155.03","obj3":"36.96","obj4":"148.99"}
{"id":"13","obj1":"133.93","obj2":"142.79","obj3":"39.91","obj4":"98.30"}
Now i want to convert them to json array , i got a solution like below
let dataArray = dataString.split('\n');
//remove white spaces and commas etc
dataArray = dataArray.filter(d=> d.length >2);
//change string to json
dataArray = dataArray.map(d=> JSON.parse(d));
Now the problem is that i have splitted them with new line and wont work if the json is compressed or data itself can have new line.
What is the best way to handle this situation. i want the output like below
[{"id":"1","obj1":"191.25","obj2":"11.81","obj3":"3.44","obj4":"15.62"},
{"id":"2","obj1":"642.00","obj2":"4.33","obj3":"0.00","obj4":"11.33"},
{"id":"3","obj1":"153.76","obj2":"94.77","obj3":"16.80","obj4":"29.79"},
{"id":"4","obj1":"61.71","obj2":"0.43","obj3":"0.00","obj4":"8.14"},
{"id":"5","obj1":"194.33","obj2":"108.89","obj3":"14.13","obj4":"168.60"},
{"id":"6","obj1":"204.31","obj2":"137.41","obj3":"34.76","obj4":"193.16"},
{"id":"7","obj1":"199.53","obj2":"34.53","obj3":"16.29","obj4":"26.56"},
{"id":"8","obj1":"77.33","obj2":"5.00","obj3":"12.50","obj4":"0.00"},
{"id":"9","obj1":"128.54","obj2":"101.60","obj3":"15.76","obj4":"46.23"},
{"id":"10","obj1":"107.00","obj2":"116.67","obj3":"34.42","obj4":"8.75"},
{"id":"12","obj1":"206.05","obj2":"155.03","obj3":"36.96","obj4":"148.99"},
{"id":"13","obj1":"133.93","obj2":"142.79","obj3":"39.91","obj4":"98.30"}
]
#sumit
please take a look at this solution.
let dataString=`{"id":"1","obj1":"191.25","obj2":"11.81","obj3":"3.44","obj4":"15.62"}
{"id":"2","obj1":"642.00","obj2":"4.33","obj3":"0.00","obj4":"11.33"}
{"id":"3","obj1":"153.76","obj2":"94.77","obj3":"16.80","obj4":"29.79"}
{"id":"4","obj1":"61.71","obj2":"0.43","obj3":"0.00","obj4":"8.14"}
{"id":"5","obj1":"194.33","obj2":"108.89","obj3":"14.13","obj4":"168.60"}
{"id":"6","obj1":"204.31","obj2":"137.41","obj3":"34.76","obj4":"193.16"}
{"id":"7","obj1":"199.53","obj2":"34.53","obj3":"16.29","obj4":"26.56"}
{"id":"8","obj1":"77.33","obj2":"5.00","obj3":"12.50","obj4":"0.00"}
{"id":"9","obj1":"128.54","obj2":"101.60","obj3":"15.76","obj4":"46.23"}
{"id":"10","obj1":"107.00","obj2":"116.67","obj3":"34.42","obj4":"8.75"}
{"id":"12","obj1":"206.05","obj2":"155.03","obj3":"36.96","obj4":"148.99"}
{"id":"13","obj1":"133.93","obj2":"142.79","obj3":"39.91","obj4":"98.30"}`;
let dataArray = dataString.match(/{(?:[^{}]*|(R))*}/g);
dataArray = dataArray.map(d=> JSON.parse(d));
console.log(dataArray);
Yeah, it is not a very good idea to concatenate objects into a string like that. If you don't have any other choice, however, something like that should do the trick:
const initialString = `{"id":"1","obj1":"191.25","obj2":"11.81","obj3":"3.44","obj4":"15.62"}
{"id":"2","obj1":"642.00","obj2":"4.33","obj3":"0.00","obj4":"11.33"}
{"id":"3","obj1":"153.76","obj2":"94.77","obj3":"16.80","obj4":"29.79"}
{"id":"4","obj1":"61.71","obj2":"0.43","obj3":"0.00","obj4":"8.14"}
{"id":"5","obj1":"194.33","obj2":"108.89","obj3":"14.13","obj4":"168.60"}
{"id":"6","obj1":"204.31","obj2":"137.41","obj3":"34.76","obj4":"193.16"}
{"id":"7","obj1":"199.53","obj2":"34.53","obj3":"16.29","obj4":"26.56"}
{"id":"8","obj1":"77.33","obj2":"5.00","obj3":"12.50","obj4":"0.00"}
{"id":"9","obj1":"128.54","obj2":"101.60","obj3":"15.76","obj4":"46.23"}
{"id":"10","obj1":"107.00","obj2":"116.67","obj3":"34.42","obj4":"8.75"}
{"id":"12","obj1":"206.05","obj2":"155.03","obj3":"36.96","obj4":"148.99"}
{"id":"13","obj1":"133.93","obj2":"142.79","obj3":"39.91","obj4":"98.30"}`;
const json = `[${initialString.replace(/}\s*{/g, '},{')}]`;
const array = JSON.parse(json);

Get string data from generateDataKeyPairWithoutPlaintext()

I am trying to get string data from return values of AWS KMS call (Node.js SDK):
const pair = await kms.generateDataKeyPairWithoutPlaintext(params);
It returns both pair.PrivateKeyCiphertextBlob and pair.PublicKey as Uint8Array blobs. I need to make a base64 string out first and plain text out of the second.
I. think I got the first one:
const buff = Buffer.from(pair.PrivateKeyCiphertextBlob);
const privateKey = buff.toString('base64');
(though I am not sure) and I am really struggling to extract plain text out of the second. Something like
const publicKey = Buffer.from(pair.PublicKey).toString();
doesn't produce desired result.
Am I doing the first one right? How do I do the second one?
Ok, I realized what I actually needed is PEM. So I put together this function:
function generatePem (publicKeyBlob) {
const publicKeyInput= {
key: publicKeyBlob,
format: 'der',
type: 'spki'
}
const publicKeyObject = Crypto.createPublicKey(publicKeyInput);
const publicKeyExportOptions = {
format: 'pem',
type: 'spki'
}
const pemPublic = publicKeyObject.export(publicKeyExportOptions);
return pemPublic;
}
based on this gist. And I just pass pair.PublicKey as a parameter.

ReactJS - How to skip empty rows in excel while reading with xlsx

I'm successfully reading my Excel file in React by following this SO thread as.
var reader = new FileReader();
reader.onload = function (e) {
var data = e.target.result;
let readedData = XLSX.read(data, {type: 'binary'});
const wsname = readedData.SheetNames[0];
const ws = readedData.Sheets[wsname];
/* Converts a worksheet object to an array of JSON objects*/
const parsedData = XLSX.utils.sheet_to_json(ws, {header:1});
console.log(parsedData);
}
reader.readAsBinaryString(fileName)
But having a simple problem, i.e., it's reading empty rows as well and causing empty entries in array.
Output of console.log(parsedData); in the above code is
I know a quick hack is to remove empty entries from the array but I want to know a better approach to avoid this problem even happening.
Edit - It's "blankrows" and not "blankRows"
I did a search and came across a similar question on gitmemory here, which shows that there's a blankRows property you can set to false in order to skip blank rows, which would look like this with your implementation:
/* Converts a worksheet object to an array of JSON objects*/
const parsedData = XLSX.utils.sheet_to_json(ws, {
header:1,
blankrows: false
});

Parse json array using javascript

I have a json arry
var students = {"apResults":[{"offid":"267","item_name":"","offer_name":"fsdfsf","stlongitude":"77.5945627","stlatitude":"12.9715987"},
{"offid":"265","item_name":"","offer_name":"vess offer shops","stlongitude":"","stlatitude":""},
{"offid":"264","item_name":"","offer_name":"vess ofer shop","stlongitude":"","stlatitude":""},
{"offid":"263","item_name":"","offer_name":"ofer frm vess","stlongitude":"77.5943760","stlatitude":"12.9716060"},
{"offid":"262","item_name":"","offer_name":"offer hungamma","stlongitude":"77.5943760","stlatitude":"12.9716060"},
{"offid":"261","item_name":"","offer_name":"offer hungamma","stlongitude":"77.5943760","stlatitude":"12.9716060"},
{"offid":"260","item_name":"","offer_name":"offer1","stlongitude":"77.5943760","stlatitude":"12.9716060"},
{"offid":"259","item_name":"","offer_name":"offer","stlongitude":"77.5943760","stlatitude":"12.9716060"}]}
How i can parse this json arry using json.parse. I have tried this code
for(i=0;i<students.apResults.length;i++)
{
var contact = JSON.parse(students.apResults);
var offid = contact.offid;
alert(offid)
}
But its giving an error JSON.parse: unexpected character.Edited my question
That's not a json string, that's a regular javascript variable:
for(i=0;i<students.Maths.length;i++)
{
var contact = students.Maths[i];
var fullname = contact.Name;
alert(fullname)
}
for(i=0;i<students.apResults.length;i++)
{
var contact = JSON.parse(students.apResults[i].offid);
alert(contact)
}
JSON parses strings, not objects/arrays.
why need parsing when you can access it like students.Maths[i].Name
students is not a JSON array, it's an actual array. You don't have to parse because it's not a string. So you can access directly to the data you need:
for(i=0;i<students.Maths.length;i++) {
var contact = students.Maths[i];
var fullname = contact.Name;
alert(fullname)
}
You can't parse students because is not a JSON. It's simple object.
However this will work:
var students = JSON.stringify(students); // if you want to send data
students = JSON.parse(students); // after receiving make a object from it
//use like any object
for(i=0;i<students.Maths.length;i++)
{
var contact = students.Maths[i];
var fullname = contact.Name;
alert(fullname)
}
Of course it doesn't make sense to write it that way unless you send students data to other site or program.
Edit:
You don't need JSON in this code at all. But if you want to test JSON.parse() do it this way:
var students = { ... } // your data
var students = JSON.stringify(students); // students is `object`, make it `string`
students = JSON.parse(students); // now you can parse it, `students` is object again
for(i=0;i<students.apResults.length;i++) {
var contact = students.apResults; // no JSON
var offid = contact.offid;
alert(offid)
}
That should work.
What you have is a javascript object. So, you won't need the JSON.parse
for(i=0;i<students.Maths.length;i++)
{
var contact = students.Maths[i]);
var fullname = contact.Name;
alert(fullname)
}
this should be ok
The idea of JSON is for the exchange of objects represented as a structured string (in a nutshell). What you've got there is simply an object. It's unnecessary (and impossible) to parse and object that isn't JSON into a javascript object; what you have is the outcome of what you would expect from a parsed JSON string.

Categories

Resources