Encoding Text to Base64 and decoding back to JSON - node.js

I am trying to encode a text to Base64 and using NodeJS, and then while getting the data I am decoding it back from Base64. Now I need to change the data into JSON so I could fill the relevant fields but its not converting to JSON.
Here is my code:
fs.readFile('./setting.txt', 'utf8', function(err, data) {
if (err) throw err;
var encodedData = base64.encode(data);
var decoded = base64.decode(encodedData).replace(/\n/g, '').replace(/\s/g, " ");
return res.status(200).send(decoded);
});
In setting.txt I have the following text:
LENGTH=1076
CRC16=28653
OFFSET=37
MEASUREMENT_SAMPLING_RATE=4
MEASUREMENT_RANGE=1
MEASUREMENT_TRACE_LENGTH=16384
MEASUREMENT_PRETRIGGER_LENGTH=0
MEASUREMENT_UNIT=2
MEASUREMENT_OFFSET_REMOVER=1
This decodes the result properly but when I use JSON.parse(JSON.stringify(decoded ) its not converting to JSON.
Can someone help me with it.

Try below snippet
let base64Json= new Buffer(JSON.stringify({}),"base64").toString('base64');
let json = new Buffer(base64Json, 'ascii').toString('ascii');

What does base-64 encoding/decoding have to do with mapping a list of tuples (key/value pairs) like this:
LENGTH=1076
CRC16=28653
OFFSET=37
MEASUREMENT_SAMPLING_RATE=4
MEASUREMENT_RANGE=1
MEASUREMENT_TRACE_LENGTH=16384
MEASUREMENT_PRETRIGGER_LENGTH=0
MEASUREMENT_UNIT=2
MEASUREMENT_OFFSET_REMOVER=1
into JSON?
If you want to "turn it (the above) into JSON", you need to:
Decide on what its JSON representation should be, then
Parse it into its component bits, convert that into an appropriate data struct, and then
use JSON.stringify() to convert it to JSON.
For instance:
function jsonify( document ) {
const tuples = document
.split( /\n|\r\n?/ )
.map( x => x.split( '=', 2) )
.map( ([k,v]) => {
const n = Number(n);
return [ k , n === NaN ? v : n ];
});
const obj = Object.fromEntries(tuples);
const json = JSON.stringify(obj);
return json;
}

Related

Translate simple text to json with node.js

today i'd like to translate a text to json data
exemple :
1 kokoa#0368's Discord Profile Avatar kokoa#0000 826
2 Azzky 陈东晓#7475's Discord Profile Avatar Azzky 陈东晓#0000 703
3 StarKleey 帅哥#6163's Discord Profile Avatar StarKleey 帅哥#0000 640
to =>
{
"kokoa#0000": "826",
"Azzky 陈东晓#0000": "703",
"StarKleey 帅哥#0000": "640"
}
for the moment i have this one :
fs.appendFile(`./Text/mess.txt`, `${body.replace(/s Discord Profile Avatar/g, '').split(/[\n \t ' ']/)}`, function (err) {
So the result is this one =>
1,kokoa#0368,,kokoa#0000,826
2,Azzky 陈东晓#7475,,Azzky 陈东晓#0000,703
3,StarKleey 帅哥#6163,,StarKleey 帅哥#0000,640
But i would like delete firsts numbers, delete the duplicate array
and make this one on .json
Someone know how can i do this ? And if i need new method to make this one, it's not a problem.
Thank you.
You can read file line by line and convert each line to a 2-elements array with key and value. For example, first line can be converted to:
['kokoa#0000','826']
As you can se 0 index is a key and 1 index is a value. When you convert all lines to this kind of array you can reduce it to an object and convert it to JSON.
See example method:
function convertLinesToJson(lines) {
const dpaText = "Discord Profile Avatar";
const jsonObject = lines
//only with 'Discord ...' text
.filter(line => line.includes(dpaText))
//get what is after 'Discord ...' text and split into 2-elements array
.map(line => {
const index = line.indexOf(dpaText) + dpaText.length;
const keyValue = line.substr(index).trim().split(/[ ]{4}/);
return keyValue;
})
// convert [key, value] array into an object
.reduce((accumulator, currentValue) => {
accumulator[currentValue[0]] = currentValue[1];
return accumulator;
}, {});
//convert object to JSON
return JSON.stringify(jsonObject);
}
Usage:
let lines = [
"1 kokoa#0368's Discord Profile Avatar kokoa#0000 826",
"2 Azzky 陈东晓#7475's Discord Profile Avatar Azzky 陈东晓#0000 703",
"3 StarKleey 帅哥#6163's Discord Profile Avatar StarKleey 帅哥#0000 640"
];
const json = convertLinesToJson(lines);
console.log(json);
Above example code prints:
{"kokoa#0000":"826","Azzky 陈东晓#0000":"703","StarKleey 帅哥#0000":"640"}
See also:
Read a file one line at a time in node.js?

Cannot access json values after converting from xml using xml-js parser

I parse the xml using the following code
var convert = require('xml-js');
var xml = require('fs').readFileSync('./2B2DE7DD-FD11-4F2C-AF0D-A244E5977CBA.xml', 'utf8');
result = convert.xml2json(xml, { spaces: 4});
The result throws the following JSON
{
"declaration": {
"attributes": {
"version": "1.0",
"encoding": "utf-8"
}
}
}
However if i try accesing "declaration" using result["declaration"]the console returns undefined
Should i use another parser or is there something wrong with getting the value.
Please use xml2js instead of xml2json if you want it return object.
result = convert.xml2js(xml, options); // to convert xml text to javascript object
result = convert.xml2json(xml, options); // to convert xml text to json text
The data type of result is String, not JavaScript object. That is, the convert.xml2json(xml, { spaces: 4}); statement will return a JSON String, not JS object.
To access declaration, you need to parse the JSON string to object:
var convert = require('xml-js');
var xml = require('fs').readFileSync('./2B2DE7DD-FD11-4F2C-AF0D-A244E5977CBA.xml', 'utf8');
result = convert.xml2json(xml, { spaces: 4});
result = JSON.parse(result);

Convert the object into a string and bring in the necessary form

An object comes to me. I write the variable key and the value through the loop:
let update_info = [];
for (let[key, value] of Object.entries(req.body)) {
update_info.push(`${key} = ${value}`);
}
console.log(JSON.parse(update_info));
Output to console:
undefined:1
user_name = name,user_email = #email.com,user_password = 12345678,about = aboutaboutaboutabout
^
SyntaxError: Unexpected token u in JSON at position 0
Why it happens?
I need to be displayed in the console like this:
'user_name' = 'name','user_email' = '#email.com','user_password' = '12345678','about' = 'aboutaboutaboutabout
How do i implement this?
I've reproduced your code like this and all you need to do is
JSON.stringify turns a JavaScript object into JSON text and stores that JSON text in a string.
JSON.parse turns a string of JSON text into a JavaScript object.
let obj = {
"welcome": "hello",
"reply": "hi"
}
let update_info = [];
for (let[key, value] of Object.entries(obj)) {
update_info.push(`${key} = ${value}`);
}
console.log(JSON.stringify(update_info));
Try the below code:
You need not to parse it using JSON.parse because the array is not yet stringified, so you should use toString() to achieve the desired result
let update_info = [];
for (let[key, value] of Object.entries(req.body)) {
update_info.push(`'${key}' = '${value}'`);
}
console.log(update_info.toString());
If you are interested in printing the Object key value pair in the console to have better view use
console.log(JSON.stringify(object, undefined, 2))
This will print the object in proper format indented by 2 spaces

Unexpected token : in JSON at position 603069

I receive the below object in my service but when I am parsing this object I get the error
SyntaxError: Unexpected token : in JSON at position 603069
Code:
var data1 = [];
// Process a chunk of data. This may be called multiple times.
req
.on("data", function(chunk) {
// Append to buffer
data1.push(chunk);
})
.on("end", function() {
var buffer = Buffer.concat(data1);
console.info("Buffer Data Request Body: " + buffer);
buffer = buffer.toString("utf8");
var partsOfStr = buffer.split("&");
//This line gives error
var obj = JSON.parse(
decodeURI(buffer.replace(/&/g, '","').replace(/=/g, '":"'))
);
Object:
{
"type" : "NewThreadVoice",
"incidentId": "398115",
"channel" : "Mobile",
"data": a huge base 64 string
"fileName": "1.aac",
"contentType" : "aac",
"contactId" : "954344"
}
When I reduce the base64 (value of data) to half it works.
A base64 string is not necessary to contain only one "=" character. This character is used for padding (for more information see Why does a base64 encoded string have an = sign at the end )
For example, the codification of home in base64 is aG9tZQ==. Using your code ( .replace(/=/g, '":"') ), this will be transformed into aG9tZQ":"":"
You should use .replace(/=+/g, '":"') for replacing all consecutive = chars.

Array of json inside string to Array of json nodejs

I am having string in two format as
[{"a":"a1"},{"a":"a2"}]'
I actually extract it in array:
[{"a":"a1"},{"a":"a2"}]
How to convert it?
Use JSON.parse()
const string = '[{"a":"a1"},{"a":"a2"}]'
const res = JSON.parse(string)
console.log('Result : ', res)
here is your string as arrayString:
const arrayString = `[{"a":"a1"},{"a":"a2"}]`;
JSON.parse(arrayString); // here you will find your desired result.
you can use JSON.parse to parse data JSON that is in string format

Resources