Source an object from a text file in javascript? - javascript

How do you source the data of multiple objects from a text file in JavaScript? I'm creating a program that will work with employee data and each employee will be treated as an object; I want the object data to come from an external source (i.e. a text file or an Excel spreadsheet), instead of having to explicitly write out the data for each employee within the code of the program. The multiple employee objects will be pushed into an array and then I'll interact with them in various ways. In the code below, I've had to explicitly write out employee data (see below). I want to source that data from some external source instead. Thanks!
function Employee (name, roomID, email)
{
this.name = name;
this.roomID = roomID;
this.email = email;
}
function EList()
{
this.employees = [];
this.firstindex = 0;
}
var employeeList = new EList();
var employee1 = new Employee("Aman Mundra", "D3-1", "aman.s.mundra#gmail.com"); //parameters inside parenthesis
var employee2 = new Employee("John Doe", "D4-1", "john.doe#gmail.com");
var employee3 = new Employee("Jane Doe", "D4-2", "jane.doe#gmail.com");
employeeList.employees.push(employee1, employee2, employee3)

What you are talking about is JSON. Make sure you are using JSON and the functions are already written for you. See json.com and json.org.
Particularly you would use JSON.parse to parse your text file, which would come in the form of a string after you have ajaxed your file in.
Here is the documentation for JSON.parse.

You might be looking for something along these lines if you can work with a CSV file: Javascript loading CSV file into an array
Why JavaScript? What are the other moving parts?

Related

How to write and read an array of objects to a file

I have this array of objects:
var people = {name:'list 1',mode:0,friends:[{user:1,code:'red'},{user:2,code:'blue'}]};
I want to write it to a file so if the node server crashes I dont lose the data. I did this:
//define variables from file
var file = "../../people.txt";
var open = fs.readFileSync(file);
va data = open.toString();
var name = data.name;
var mode = data.mode;
var friends = data.friends;
whenever a variable changes I save it to a file like this:
function update() {
//dosomething
name = 'new list';
mode = 1;
friends = [{user:4,code:'red'},{user:6,code:'blue'}]
fs.writeFileSync(file,`{name:'${name}',mode:${mode},friends:${friends}'}`,{encoding:'utf8',flag:'w'});
}
This is output onto the file
{name:'list 1',mode:0,friends:[object, object]}
and the data cant be read at all. What am I supposed to do here?
Thank you.
You should convert the JSON data into a string format using JSON.stringify() before writing it to a file, and when reading them out, you should parse the string into JSON using JSON.parse()
More details are here and how to read/write JSON files

How to access a json object in javascript files from a model passed to the view

I have a JSON object in my database that contains html inside it. I pass the object as part of a model to my view. I need to access the object and read it in the javascript files for the page. However when i try and assign the object to a global variable in my html file i cannot access it in my javascript file.
I tried reading the object as a string it returns decoded html (
"page-1":) which i cant do anything with. If i call #Html.Raw(#Model.CourseContent.ExpectedResult) it created the JSON object as expected. However in my javascript file it is listed as undefined. I have no idea how to solve this.
#model DataTransferObjects.Models.UserCourseAndContent
<script>
var totalPages = '#Model.CourseContent.TotalPages';
var expectedResults = #HTML.Raw(#Model.CourseContent.ExpectedResult)
</script>
The json object that comes out when i use the above code looks like
var expectedResults = {
"page-1": "<head></head><body></body>",
"page-3": "<head></head><body><h1>My Cool News Article</h1><p>Welcome
to my news article, you’ll find some cool news here.</p>
<Our most recent
news</<p>Below you’ll find my most recent news!</p></body>"
};
I expected it to be an actual json string but instead ive got an object (?) i am confused as to how to decode the html out of it then turn the resulting json obejct into a json string to be read in the javascript file.
Any help would be great!
var expectedResults = {
"page-1": "<head></head><body></body>",
"page-3": "<head></head><body><h1>My Cool News Article</h1><p>Welcome
to my news article, you’ll find some cool news here.</p>
<Our most recent
news</<p>Below you’ll find my most recent news!</p></body>"
};
// Parse JSON
const parsedJSON = JSON.parse(JSON.stringify(expectedResults));
// Access to properties
const page-1 = parsedJSON['page-1'];
const page-3 = parsedJSON['page-3'];

How to store and get data from a json file with javascript?

I would like to create a little kind of CMS. For that I want to code a function, which automatically creates a list of the files, which were created with the CMS. This list sould be display in a html file and styled with CSS. For that I want to create a json-File, in which i store the title and the location of the new file.
Then it should look like this:
{
"new_sites":
{
"title": "source",
"otherTitle": "otherSource"
}
}
Now I want to know, how I can get (or store new) data from the json-File and use it as variables in javascript so that I can display it on the html page.
Given these three variables:
var myNewSite = 'newSite';
var myNewTitle = 'newTitle';
var myNewSource = 'newSource';
and your final json variable initialized in this way:
var myJson = {};
You could simply:
myJson[myNewSite] = {
myNewTitle: myNewSource
};
You can use Jquery api to get data from json-file.Suppose you have a data.json file in directory.
<script>
var container={};
$.getJSON('data.json', function(data) {
container=data;
});
</script>

how to pass complicated data between mvc and javascript

I'm trying to build a UI with two dropdowns. The first one is "category", the second one is "sub-category". I can build a static list of "category" in my razor view. I want the "sub-category" item list to be dynamically updated when "category" is changed. I'm trying to pass all category information from server side to client side since the list is not big and there is no security issue. But I cannot find a good way to format my data and transfer it to client side. I can generate a json object with all of my category trees using the following code:
ExpandoObject catToSubcatMap = new ExpandoObject();
foreach (var cat in repository.Categories)
{
var subcats = repository.SubCategories.Where(s => s.ParentID == cat.CategoryID);
List<Object> subcatNameList = new List<object>();
foreach(var subcat in subcats)
{
subcatNameList.Add(new { Name = subcat.Name });
}
AddProperty(catToSubcatMap, cat.Name, subcatNameList);
}
Session["CatToSubcatMap"] = JsonConvert.SerializeObject(catToSubcatMap, Newtonsoft.Json.Formatting.Indented, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });
The json itself looks perfect. But when I tried to read the value from my jQuery function, it failed:
var sss = '#Session["CatToSubcatMap"]';
It seems like there are too many special characters in the json string. My generic question is: how should I format and pass complicated data between server and client. Using Viewbag or Session, which one is preferred?
Thanks
Chris
You can do what you are trying to do; what you have should be formatted correctly, but you just have to include Html.Raw.
var sss = #(
Html.Raw(Session["CatToSubcatMap"].ToString())
);
Raw will essentially write out directly to the response without encoding the contents, which is what likely was happening.

How go I get csv data into netsuite?

I've got an update to my question.
What I really wanted to know was this:
How do I get csv data into netsuite?
Well, it seems I use the csv import tool to create a mapping and use this call to import the csv nlapiSubmitCSVImport(nlobjCSVImport).
Now my question is: How do I iterate through the object?!
That gets me half way - I get the csv data but I can't seem to find out how I iterate through it in order to manipulate the date. This is, of course, the whole point of a scheduled script.
This is really driving me mad.
#Robert H
I can think of a million reasons why you'd want to import data from a CSV. Billing, for instance. Various reports on data any company keeps and I wouldn't want to keep this in the file cabinet nor would I really want to keep the file at all. I just want the data. I want to manipulate it and I want to enter it.
Solution Steps:
To upload a CSV file we have to use a Suitelet script.
(Note: file - This field type is available only for Suitelets and will appear on the main tab of the Suitelet page. Setting the field type to file adds a file upload widget to the page.)
var fileField = form.addField('custpage_file', 'file', 'Select CSV File');
var id = nlapiSubmitFile(file);
Let's prepare to call a Restlet script and pass the file id to it.
var recordObj = new Object();
recordObj.fileId = fileId;
// Format input for Restlets for the JSON content type
var recordText = JSON.stringify(recordObj);//stringifying JSON
// Setting up the URL of the Restlet
var url = 'https://rest.na1.netsuite.com/app/site/hosting/restlet.nl?script=108&deploy=1';
// Setting up the headers for passing the credentials
var headers = new Array();
headers['Content-Type'] = 'application/json';
headers['Authorization'] = 'NLAuth nlauth_email=amit.kumar2#mindfiresolutions.com, nlauth_signature=*password*, nlauth_account=TSTDRV****, nlauth_role=3';
(Note: nlapiCreateCSVImport: This API is only supported for bundle installation scripts, scheduled scripts, and RESTlets)
Let's call the Restlet using nlapiRequestURL:
// Calling Restlet
var output = nlapiRequestURL(url, recordText, headers, null, "POST");
Create a mapping using Import CSV records available at Setup > Import/Export > Import CSV records.
Inside the Restlet script Fetch the file id from the Restlet parameter. Use nlapiCreateCSVImport() API and set its mapping with mapping id created in step 3. Set the CSV file using the setPrimaryFile() function.
var primaryFile = nlapiLoadFile(datain.fileId);
var job = nlapiCreateCSVImport();
job.setMapping(mappingFileId); // Set the mapping
// Set File
job.setPrimaryFile(primaryFile.getValue()); // Fetches the content of the file and sets it.
Submit using nlapiSubmitCSVImport().
nlapiSubmitCSVImport(job); // We are done
There is another way we can get around this although neither preferable nor would I suggest. (As it consumes a lot of API's if you have a large number of records in your CSV file.)
Let's say that we don't want to use the nlapiCreateCSVImport API, so let's continue from the step 4.
Just fetch the file Id as we did earlier, load the file, and get its contents.
var fileContent = primaryFile.getValue();
Split the lines of the file, then subsequently split the words and store the values into separate arrays.
var splitLine = fileContent.split("\n"); // Splitting the file on the basis of lines.
for (var lines = 1,count=0; lines < splitLine.length; lines++)
{
var words = (splitLine[lines]).split(","); // words stores all the words on a line
for (var word = 0; word < words.length; word++)
{
nlapiLogExecution("DEBUG", "Words:",words[word]);
}
}
Note: Make sure you don't have an additional blank line in your CSV file.
Finally create the record and set field values from the array that we created above.
var myRec = nlapiCreateRecord('cashsale'); // Here you create the record of your choice
myRec.setFieldValue('entity', arrCustomerId[i]); // For example, arrCustomerId is an array of customer ID.
var submitRec = nlapiSubmitRecord(myRec); // and we are done
fellow NetSuite user here, I've been using SuiteScripts for a while now but never saw nlobjCSVImport object nor nlapiSubmitCSVImport .. I looked in the documentation, it shows, but there is no page describing the details, care to share where you got the doc from?
With the doc for the CSVImport object I might be able to provide some more help.
P.S. I tried posting this message as a comment but the "Add comment" link didn't show up for some reason. Still new to SOF
CSV to JSON:
convert csv file to json object datatable
https://code.google.com/p/jquery-csv/
If you know the structure of the CSV file, just do a for loop and map the fields to the corresponding nlapiSetValue.
Should be pretty straightforward.

Categories

Resources