Json File Creation in nodeJS - json

I need to create a JSON file in the below format in nodeJS also i need to traverse into the particular position and add the values if any. I have done it in Java, but no idea in NodeJs. It will be helpful if someone helps me. Thanks.

If my understanding is correct, you are using Protractor to automate AngularJS tests and write the results as JSON for reporting / for parsing it back once done?
If that's the case, you could simply store the results as a Object in Javascript and write it out using fs node package.
Writing the JSON Report file
var fs = require('fs');
//..Protractor .. and other logic..
var results = { Project : "xxx" , ....};
//...more of that assignment....
//You could use JSON.parse() or JSON.stringify() to read/convert this object to string vice versa and fs package to read/write it to file.
fs.writeFile("/tmp/testreport.json", JSON.stringify(results), function(err) {
if(err) {
return console.log(err);
}
console.log("The test report file was saved as JSON file!");
});

Related

Convert data from XML to JSON React.js

Im trying to build an application that fetches data from an web API that returns XML. I want this data in JSON instead, but the API does not support that.
How do i fetch the data and convert it to JSON?
I tried to use xml2js and it seems to work, but i dont understand how to save it as an object so i can use it in my app.
async componentDidMount(){
const url = "this is where the APIurl are";
fetch(url)
.then(res => res.text())
.then(body => parseString(body, function (err, result) {
console.log(result);
})
);
}
result seems to return the data as json, but i cant figure out how to use the data as an object later.
Your best option is to use an external lib to do that. A quick search in google and I found this one https://www.npmjs.com/package/xml-js.
You should also check this question: Convert XML to JSON (and back) using Javascript
To store it on your app you should grab what you need from the parsed XML and put it on the state.

Read local JSON files when dynamically creating functional tests in Intern

I am creating functional tests dynamically using Intern v4 and dojo 1.7. To accomplish this I am assigning registerSuite to a variable and attaching each test to the Tests property in registerSuite:
var registerSuite = intern.getInterface('object').registerSuite;
var assert = intern.getPlugin('chai').assert;
// ...........a bunch more code .........
registerSuite.tests['test_name'] = function() {
// READ JSON FILE HERE
var JSON = 'filename.json';
// ....... a bunch more code ........
}
That part is working great. The challenge I am having is that I need to read information from a different JSON file for each test I am dynamically creating. I cannot seem to find a way to read a JSON file while the dojo javascript is running (I want to call it in the registerSuite.tests function where it says // READ JSON FILE HERE). I have tried dojo's xhr.get, node's fs, intern's this.remote.get, nothing seems to work.
I can get a static JSON file with define(['dojo/text!./generated_tests.json']) but this does not help me because there are an unknown number of JSON files with unknown filenames, so I don't have the information I would need to call them in the declare block.
Please let me know if my description is unclear. Any help would be greatly appreciated!
Since you're creating functional tests, they'll always run in Node, so you have access to the Node environment. That means you could do something like:
var registerSuite = intern.getPlugin('interface.object').registerSuite;
var assert = intern.getPlugin('chai').assert;
var tests = {};
tests['test_name'] = function () {
var JSON = require('filename.json');
// or require.nodeRequire('filename.json')
// or JSON.parse(require('fs').readFileSync('filename.json', {
// encoding: 'utf8'
// }))
}
registerSuite('my suite', tests);
Another thing to keep in mind is assigning values to registerSuite.tests won't (or shouldn't) actually do anything. You'll need to call registerSuite, passing it your suite name and tests object, to actually register tests.

How to add path to export my data to file .csv

I am using lib in npm for project angular call json2csv for export JSON to file.csv (excel)
Here is my code:
const fields = ['id', 'name'];
const opts = { fields };
try {
const parser = new json2csv.Parser(opts);
const csv = parser.parse(this.data);
console.log(csv);
} catch (err) {
console.error(err);
}
Printing object is correct data but not create file.
Can anyone help me when add filename and path in my code?
The json2csv node_module that you're trying to use in your Angular App is not supposed to be used there. It's supposed to be used on your NodeJS backend.
Your Frontend/Client is not responsible for writing files to the system. Your Backend/Server is.
Ideally, you should be creating a REST API to which, you'll be passing the JSON to be written in a CSV file as a Request Payload.
Your NodeJS Backend can then respond to that request with the downloadable CSV file that is generated by using the json2csv node_module

Parse and convert xls file (received from GET request to URL) to JSON without writing to disk

The title says everything.
I want to get an xls file from a third party server. (said service keeps fueling
records, and they do not expose any kind of api, only the excel file).
Then parse that file with a library like node-excel-to-json, and convert it into JSON format I can use to import the data in mongo.
I want to manipulate the file in-memory, without writing it to disk.
So, say I am getting the file with this code,
parseFuelingReport() {
let http = require('http');
let fs = require('fs');
// let excel2Json = require('node-excel-to-json');
let file = fs.createWriteStream("document.xls");
let request = http.get("http://www.everydayexcel.com/files/Excel_Test_Basic_1_cumulative_sum.xls", function (response) {
});
},
I want to load the response in memory and parse it with something like
excel2Json(/* this is supposed to be the path to the xls file */, {
'convert_all_sheet': false,
'return_type': 'File',
'sheetName': 'survey'
}, function (err, output) {
console.log('err, res', err, output);
});
I assume you are using https://github.com/kashifeqbal/node-excel-to-json, which is available as node package.
If you take a look at this line,
you can see, two things:
It calls XLSX.readFile(filePath);, what will load a file from disk. Hard to call with an in-memory object in.
Internally it uses a XLSX package, most likely this one: https://www.npmjs.com/package/xlsx
The XLSX API seems not as convenient as the excel2Json, but it provides a read() function which takes a JavaScript object:
/* Call XLSX */
var workbook = XLSX.read(bstr, {type:"binary"});
Hope this helps

Nodejs write json to a file

I just started learning nodejs. I am currently working with sockets and made chat program.
I want to save entire chat to a json file. Currently my code is this :
socket.on('chat', function (data) {
message = {user : data.message.user, message : data.message.message};
chat_room.sockets.emit('chat', {message: message});
jsonString = JSON.stringify(message);
fs.appendFile("public/chat.json", jsonString, function(err) {
if(err) {
console.log(err);
} else {
console.log("The file was saved!");
}
});
});
This is currently working perfect, but the json which is written in file is wrong.
This gave me a wrong json
{"user":"niraj","message":"hw r u?"}{"user":"ntechi","message":"hello"}{"user":"ntechi","message":"hw r u?"}
The above code is called when message is triggered. I want json in this format
{"user":"awd","message":"hw r u?","user":"ntechi","message":"hello","user":"ntechi","message":"hw r u?"}
Can anyone help me in this? Thanks in advance
The first set of wrong JSON is created because you are appending a piece of JSON to a file each time you get a message.
The second set of JSON is also wrong - each property name has to be unique.
Presumably you want something like:
[
{"user":"niraj","message":"hw r u?"},
{"user":"ntechi","message":"hello"},
{"user":"ntechi","message":"hw r u?"}
]
In which case the logic you need to use is:
Read data from file
Parse data as JSON and assign to a variable
In the event of an error, assign an empty array to that variable
push the message object onto the end of the array
stringify the array
Overwrite the file with the new string