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

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

Related

Encoding Text to Base64 and decoding back to JSON

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

How to parse JSON with escaped doublequotes, using node.js?

Here is an example of some JSON I am working with:
{"name":"John","attributes":"{\"key\":\"value\"}"}
Here it is again, in a more readable format:
{
"name": "John",
"attributes": "{\"key\":\"value\"}"
}
Notice above that the doublequotes surrounding key and value are escaped. That's necessary, and is valid JSON (checked at jsonlint.com).
I am trying to get the value of "name", but the escaped doublequotes are causing an error.
What am I doing wrong in my node.js code?
var theString = '{"name":"John","attributes":"{\"key\":\"value\"}"}';
var theJSON = JSON.parse(theString);
var theName = theJSON.name;
console.log("name = " + theName);
Below is the output. The error occurs on the 2nd line of my code, where I "JSON.parse()" the string. JSON.parse seems to be removing the backslashes, turning valid JSON into invalid JSON.
undefined:1
{"name":"John","attributes":"{"key":"value"}"}
^
SyntaxError: Unexpected token k in JSON at position 31
Since that part of the data is JSON-within-JSON, you'd parse the JSON, then parse the JSON on the attributes property:
const obj = JSON.parse(json);
obj.attributes = JSON.parse(obj.attributes);
Live Example:
const json = document.getElementById("json").textContent;
const obj = JSON.parse(json);
obj.attributes = JSON.parse(obj.attributes);
console.log(obj);
<pre id="json">{
"name": "John",
"attributes": "{\"key\":\"value\"}"
}</pre>

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