Parse Json File in NodeJS displays unexpected results in Node - javascript

I have the below nodejs code that reads contents of baseline.json file and parse it. I then try to display all the Computer ID and LastReportTime. I see an odd behaviour it would not print all the ID and LastReportTime. Also, the results are different every time i run it. The json is big for me to upload here so i uploaded on Json Blob.
Nodejs Code
var fs = require('fs');
try {
var json = JSON.parse(fs.readFileSync('baseline.json'));
for (var obj in json) {
if (json.hasOwnProperty(obj)) {
console.log(obj);
console.log("\n \n");
if (obj == "BESAPI") {
for (var prop in json[obj]) {
console.log(prop);
if (prop == "Computer") {
// loop over Computer dataseries
for (var id in json[obj][prop]) {
console.log(prop + ':' + json[obj][prop][id].ID);
console.log(prop + ':' + json[obj][prop][id].LastReportTime);
}
}
}
}
}
}
} catch (err) {
console.error(err);
}
Raw JSON
https://gist.github.com/anonymous/f27f75879e48c5387a03

In your posted array, LastReportTime and ID are arrays.
Try these lines:
console.log(prop + ':' + json[obj][prop][id].ID[0]);
console.log(prop + ':' + json[obj][prop][id].LastReportTime[0]);

If you pretty print you can see the data comes in two flavors, the top portion followed by the balance of the data in a standard form which does repeat 177 times
{
BESAPI: {
$: {
xmlns:xsi: "http://www.w3.org/2001/XMLSchema-instance",
xsi:noNamespaceSchemaLocation: "BESAPI.xsd"
},
Computer: [
{
$: {
Resource: "api/computer/2431038"
},
LastReportTime: [
"Thu, 26 Feb 2015 14:54:41 +0000"
],
ID: [
"2431038"
]
},
{
$: {
Resource: "api/computer/16710075"
},
LastReportTime: [
"Thu, 26 Feb 2015 14:45:18 +0000"
],
ID: [
"16710075"
]
},
{
$: {
Resource: "api/computer/3415985"
},
LastReportTime: [
"Thu, 26 Feb 2015 14:50:52 +0000"
],
ID: [
"3415985"
]
},
{
$: {
Resource: "api/computer/11736335"
},
LastReportTime: [
"Thu, 26 Feb 2015 14:54:41 +0000"
],
ID: [
"11736335"
]
},
I am chopping out many lines her, but it ends normally as
{
$: {
Resource: "api/computer/5520740"
},
LastReportTime: [
"Thu, 12 Feb 2015 02:49:11 +0000"
],
ID: [
"5520740"
]
}
]
}
}
Using nodejs you can pretty print using :
var pretty_print = require('js-object-pretty-print').pretty;
var parsed_data = JSON.parse(data_from_file);
console.log(pretty_print(parsed_data)); // good pretty print

Related

map on the lower level key of a nested object

I had posted this question earlier but someone deleted with How can I access and process nested objects, arrays or JSON?
as possible answer. This is not helping me since a) The key 'date' is spread across several names, b)The objects comprises on arrays & objects & c) The depth at which the key 'date' is present can change.
Hence posting the question again.
I have a JS object as below
const bb = {
Harry: {
details: [
{
cat: "Life",
values: [
{
date: "2021-08-02",
level: 77.6,
},
{
date: "2021-08-03",
level: 79.1,
},
],
},
],
},
Barry: {
details: [
{
cat: "Logic",
values: [
{
date: "2021-08-02",
level: 77.6,
},
{
date: "2021-08-03",
level: 79.1,
},
],
},
],
},
};
I also have a variable defined for parsing the dates const dateParse = d3.timeParse("%Y-%m-%d")
I want to parse all the dates in the object. Since the 'date' is few levels below in the object, I am not able to figure this out. How do I go about it?
The expected output is
const bb = {
Harry: {
details: [
{
cat: "Life",
values: [
{
date: Mon Aug 02 2021 00:00:00 GMT+0530 (India Standard Time),
level: 77.6,
},
{
date: Tue Aug 03 2021 00:00:00 GMT+0530 (India Standard Time),
level: 79.1,
},
],
},
],
},
Barry: {
details: [
{
cat: "Logic",
values: [
{
date: Mon Aug 02 2021 00:00:00 GMT+0530 (India Standard Time),
level: 77.6,
},
{
date: Tue Aug 03 2021 00:00:00 GMT+0530 (India Standard Time),
level: 79.1,
},
],
},
],
},
};
You just have to loop through the objects, select the date node and execute
(new Date(datestring)).toString()
This will generate the date as specified in your output.
const bb = { Harry: { details: [{cat: "Life",values: [{date: "2021-08-02",level: 77.6},{date: "2021-08-03",level: 79.1}]}]},Barry: {details: [{cat: "Logic",values: [{date: "2021-08-02",level: 77.6},{date: "2021-08-03",level: 79.1}]}]}};
Object.values(bb).forEach((value) => {
value.details.forEach((detail) => {
detail.values.forEach((value) => {
value.date = (new Date(value.date)).toString();
})
})
});
console.log(bb);
If you want to parse all the nested date keys, you can do it recursively using the below functions
const bb = { Harry: { details: [{cat: "Life",values: [{date: "2021-08-02",level: 77.6},{date: "2021-08-03",level: 79.1}]}]},Barry: {details: [{cat: "Logic",values: [{date: "2021-08-02",level: 77.6},{date: "2021-08-03",level: 79.1}]}]}};
function traverseArray(inputArray) {
for (const arrayValue of inputArray) {
traverseObject(arrayValue);
}
}
function traverseObject(inputObject) {
for (const key in inputObject) {
const value = inputObject[key];
const valueType = typeof(value);
if (valueType == "object") {
traverseObject(value);
} else if (valueType == "array") {
traverseArray(value);
} else if (key == "date") { // since I want to parse only date keys
inputObject[key] = 'd3.timeParse("%Y-%m-%d") - Parse date here';
}
}
}
traverseObject(bb);
console.log(bb);

Send same json in the file at each script execution

I'm writting a JSON and adding into a file.
I don't know how can I add the same JSON in the same array...
When I execute the script, i need to add the new value into the file and not overwritting
I just need to append the JSON. If I use appenFile, create 3 array and I need only 1 array (Look expected result)
Need help, thanks
var table = []
table.push({"executionDate":date,
"issueID":key,
"priority":{
"jira": priority,
"computed":score1
},
"expectedValue":{
"jira": expected,
"computed":score2
}
})
var json = JSON.stringify(table);
fs.writeFile('myjsonfile.json', json, 'utf8', function (err) {
if (err) console.error(err)
})
Actual result:
[{
"executionDate": 25 / 03 / 2019,
"issueID": 1,
"priority": {
"jira": important,
"computed": 10
},
"expectedValue": {
"jira": expected,
"computed": 20
}
}]
Expected resultat if I execute the script 2 times:
[{
"executionDate": 25 / 03 / 2019,
"issueID": 1,
"priority": {
"jira": important,
"computed": 10
},
"expectedValue": {
"jira": expected,
"computed": 20
}
},
{
"executionDate": 25 / 03 / 2019,
"issueID": 1,
"priority": {
"jira": important,
"computed": 10
},
"expectedValue": {
"jira": expected,
"computed": 20
}
},
{
"executionDate": 25 / 03 / 2019,
"issueID": 1,
"priority": {
"jira": important,
"computed": 10
},
"expectedValue": {
"jira": expected,
"computed": 20
}
}]
Im not sure if i understand it well but a fast solution is:
<html>
<script>
var table = [];
console.log(table);
function findInArrAndPush(obj){
const found = table.some(el => el.issueID === obj.issueID);
if (!found) table.push(obj);
return table;
}
for(i=0;i<3;i++){
var id = i;
var objToAdd = {"executionDate":"01-01-1000",
"issueID":id,
"priority":{
"jira": "1",
"computed":"1"
},
"expectedValue":{
"jira": "2",
"computed":"2"
}
};
console.log(findInArrAndPush(objToAdd));
//ADD TO FILE HERE
}
</script>
<body>
</body>
</html>
the only thing you have to do here is print the result to the file.

How read data from a JSON arry object in Javascript

I am trying to get a value from a JSON array in Javascript :
The JSON array looks like :
[
{
"_id": 0,
"_entityMetadataList": [
{
"_metadataValue": "/storage/emulated/0/DCIM/.thumbnails/1524101696032.jpg",
},
{
"_metadataValue": "/storage/emulated/0/DCIM/.thumbnails/1524101694488.jpg",
}
],
"_timeCreated": "Tue Jan 15 06:10:04 2019\n",
"_timeUpdated": "Tue Jan 15 06:10:04 2019\n",
"objectEntity": {
"_id": 0,
"_EntitySiteGUID": -1
}
}
]
How I go about it :
app.post('/sound', function (req, res) {
let entitiesArray = req.body['filter'];
console.log('entitiesArray: ' + JSON.stringify(entitiesArray._entityMetadataList[0]._metadataValue))
(this is in a Node environment, by the way)
I, however keep getting the error :
TypeError: Cannot read property '0' of undefined
Seems you also need to pass the index for revEntitiesArray.
Try this
console.log('revEntitiesArray: ' +
JSON.stringify(revEntitiesArray[0]._revEntityMetadataList[0]._metadataValue))
Maybe this code can help
data = [
{
"_id": 0,
"_revEntityMetadataList": [
{
"_metadataValue": "/storage/emulated/0/DCIM/.thumbnails/1524101696032.jpg",
},
{
"_metadataValue": "/storage/emulated/0/DCIM/.thumbnails/1524101694488.jpg",
}
],
"_timeCreated": "Tue Jan 15 06:10:04 2019\n",
"_timeUpdated": "Tue Jan 15 06:10:04 2019\n",
"revObjectEntity": {
"_id": 0,
"_revEntitySiteGUID": -1
}
}
]`
data[0]["_revEntityMetadataList"][0]
Looks like you missed that the outermost reference is an array
revEntitiesArray[0]._revEntityMetadataList[0]._metadataValue
When in doubt, assign each part of your path expression to a local variable and step through with a debugger.

How to parse JSON with jQuery while ignoring first element?

I have JSON data in this format:
{
"status":"Good",
"open_slots":[
{
"date":"Tue, Jun 28, 2016",
"time_slot":"9:15 AM"
},
{
"date":"Tue, Jun 28, 2016",
"time_slot":"12:30 PM"
},
{
"date":"Tue, Jun 28, 2016",
"time_slot":"2:00 PM"
}
]
}
How can I ignore the 'status' portion of the data and build a list based on open_slots with jQuery?
var json = JSON.parse(input);
var json_keep = json.open_slots;
Now you can loop over just the open slots:
for (var i = 0; i < json_keep.length; i++) {
alert("Found date/time_slot: " + json_keep[i].date + "/" + json_keep[i].time_slot);
}

Unable to print json values after parsing in NodeJS

The below NodeJS code tries to convert an xml document into json and then parse it.
var fs = require('fs');
var parse = require('jsonml').parse;
var jsonML = parse(fs.readFileSync('myfile.xml'));
var jsondata = JSON.parse(jsonML);
console.log(jsondata.BESAPI.Computer[0].ID);
It works fine, but I am unable to display the correct values. An error is thrown on the line console.log(jsondata.BESAPI.Computer[0].ID);
I am trying to display the ID of each computer in the json object.
Json object
{
"BESAPI": {
"-xmlns:xsi": "http://www.w3.org/2001/XMLSchema-instance",
"-xsi:noNamespaceSchemaLocation": "BESAPI.xsd",
"Computer": [
{
"-Resource": "api/computer/2431038",
"LastReportTime": "Thu, 26 Feb 2015 14:54:41 +0000",
"ID": "2431038"
},
{
"-Resource": "api/computer/16710075",
"LastReportTime": "Thu, 26 Feb 2015 14:45:18 +0000",
"ID": "16710075"
},
{
"-Resource": "api/computer/3415985",
"LastReportTime": "Thu, 26 Feb 2015 14:50:52 +0000",
"ID": "3415985"
}]
}
}
I get this error:
Without having your original XML, I can't know for sure what's going on, but this experiment may help you with further investigations.
For an XML like
<?xml version="1.0"?>
<BESAPI>
<Computer ID="api/computer/2431038"></Computer>
<Computer ID="api/computer/16710075"></Computer>
</BESAPI>
the output from jsonML looks like this:
[ 'BESAPI',
[ 'Computer', { ID: 'abc123' } ],
[ 'Computer', { ID: 'def987' } ] ]
which doesn't resemble the JSON you gave us, but attempting to parse it gives the error you presented.
So I'm guessing that the output from jsonML isn't parsable JSON, but a nested array of sorts.

Categories