Why can't this code access my JSON file in netbeans? - javascript

So I am trying to learn Javascript. I created a JSON file called "Ancest.json". Then, in a new file on netbeans I tried to execute this code accessing that file:
var ancestry = JSON.parse(Ancest);
console.log(ancestry.length);
I am getting a rejection saying "Ancest is not defined".
What am I doing wrong? Attached is a screen shot. Thank you for your time.

JSON.parse method accepts a string which is the JSON object to be parsed into a JavaScript object.
You need to get the content of the file or to move the content of your JSON file into a string variable in the js file. Then you can parse it:
console.log(JSON.parse('{ "a": "test" }'));
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse

You need to assign a string Ancest or var Ancest = './Ancest.json'; Depending on the location and path of Ancest.json, you may have to put in the full path or linked path if the .js file exists in the same path. Also put the path in single quote or double quote. Make sure you have access to read the file.
It also needs correct file system permissions. This is all contingent on who this js is running as, delegate permissions on the parent directories, etc, etc. Chances are permissions are okay for read.

Related

I have a separate .json file, I need to iterate over the file or read through the file and do some stuff. How exactly do I do this in Javascript?

I have a folder with an html, css, json, and js file. The js file are a list of person's and what they do. I need to analyze the json file contents using javacript. I know that in C or C++ you can open the file for reading and analyze it, then close it. So, how do I do this in Javascript? And do I need to add the name of the JSON array in the .json file, or should i leave the contents as it is?
JSON screenshot image
Nothing online have worked thus far. Hopefully Stackoverflow can help.
Let's assume you're using nodeJS, you can import the json file using require .
After you've imported the json file, you can access the object as it would be a JS object.
const jsonFile = require("./pathtofile.json")
for(let obj in jsonFile) {
console.log(obj)
}

Convert js file to ulg file

I need to store javascript data into a ulg (Ulog) file. In other words, I need to create a ulg file and convert JavaScript values into ulg and then store it. Can anyone give me some ideas about this?
I had a look into PX4 but it does not support this and I haven't found any post about this either.
FYI: It is also valid the conversion of another type of file other than JavaScript as long as I can convert JavaScript into that type of file. For example: .js -> .ulg or .js -> .py -> .ulg
The end result needs to be an ulg file
I really appreciate the help!
Have a look at this link: https://github.com/PX4/pyulog
Basically, you have to call the ulog2csv script.
For example: in your log’s folder, open a terminal and enter ulog2csv log_name.ulg.

Again: how can I read a file using javascript

I could not find out why this part of my code doesn't work:
var loc = window.location.pathname;
var dir = loc.substring(0, loc.lastIndexOf('/'));
var FilePath = dir + "/" + FileName;
var file = new File("FilePath");
var reader = new FileReader();
reader.onload = function(e) {FileText = reader.result;}
reader.readAsText(file);
alert (FileText);
The intention is, I think, clear: FilePath contains the filename of a file (passed via parameter FileName) containing logging data (a plain ASCII text file, with one line per log entry), the file is located in the same directory as the web page is (loc), and I want to embed the text into my html document somewhere further down the code.
Since the logged lines are of different kinds (e.g. errors, warning, other blabla ...) each line needs to be parsed and processed.
I intended to split FileText into an array, and loop through it. I cannot, however, get readastext to work. Though, according to FireFox debugger, FilePath does contain the correct string, I get the NS_ERROR_FAILURE, which I, according to the sparse documentation I found about it, must consider to be the 'zillionst stupid way to say "File not found".
I found tons of other posts from people messing with the file API, and tons of snippets taken from the mozilla docs which don't help me out. I read that there are maybe other ways to read a file, e.g. through Ajax, JQuery ... but before I go that way ... is it really, really absolutely impossible to accomplish what I want using just plain JavaScript, and if it is possible, who can provide a code snippet?
Thanks very much,
Armin.
You have quotes around "FilePath":
var file = new File("FilePath");
This means it's going to try to load a file with the path "FilePath".
Pretty sure this is what you want:
var file = new File(FilePath);
On the other hand, Quentin is absolutely right. You're not going to be able to access local files if this code is running in a web page.
Since you are using window.location.pathname i assume that you are in a browser and want to use that code to "navigate" to files on the server based on the URL path.
I think your whole approach is wrong, and it would be a security issue to have something like that possible.
The File API can be used strictly on files selected by the user, and not on any file. The MDN description is self-explanatory:
Using the File API, which was added to the DOM in HTML5, it's now possible for web content to ask the user to select local files, then read the contents of those files. This selection can be done by either using an HTML element, or by drag and drop.
Yes, you can specify a path to any file in the File constructor method, but that doesn't mean you can access any file. Another excerpt from MDN:
This only works from privileged code, so web content can't do it. This protects users from the inherent security risks associated with allowing web content free access to the contents of their disks. If you pass a path to the File constructor from unprivileged code (such as web content), an exception will be thrown.
This code did the trick:
var objXMLhttp = new XMLHttpRequest()
objXMLhttp.open("GET",strFileName,true);
objXMLhttp.send();
and, in addition, an objXMLhttp.onreadystatechange=function() ... event handler must be implemented, which is the code acutally receiving the data, like so:
objXMLhttp.onreadystatechange=function()
{
if (objXMLhttp.readyState==4 && objXMLhttp.status==200)
{
var arrContents = objXMLhttp.responseText.split("\n"); // gotcha!
....
}
}
Easy win is to do an ajax request for the path...you should have your page that contains the js and files served by a web server. Any other way needs other priveleges and if you were to get files from a users computer without an uploader or anything like that would be a security breach

How to store config information for a ASP.NET site not in Web.Config

I need to store a file pairing colours and images for use in my JavaScript. I would have liked to use a simple CSV file and Papa Parse, but PP requires either text or a File object as input, and I can find no way of opening a File object, nor of reading the text from the CSV file. Surely my code should be allowed to read files that reside under the web site, not randomly among the file system?
My alternative is to have the end user, non-technical, edit a JSON file that is parsed by my code.
Am I wrong, or is this the case? Then maybe I should build an editor for the JSON file that simplifies the data editing for the end user.
All the file has to store is colour/image name pairs.
Have you tried using something like this? Are you getting an error? Sorry, I cannot leave comments yet.
StreamWriter _testData = new StreamWriter(Server.MapPath("~/data.txt"), true);
_testData.WriteLine(TextBox1.Text); // Write the file.
_testData.Flush();
_testData.Close(); // Close the instance of StreamWriter.
_testData.Dispose(); // Dispose from memory.

Read a file purely in javascript on Firefox OS(B2G)

I have to read a file from the file system of my phone. Essentially its to check if the file contains a word. The file is located in the /sys folder of my phone. I know I can get the contents of the File using FileReader.readAsText(file) to get the contents as a string and then parse it for the word. But how do I make the "file" object to pass to the FileReader object. Thanks in advance!
Edit: Just wanted to add here:
Can I use the File constructor here?
var file = File("/path/to/file");
You can only read data from your app folder (via XMLHttpRequest) and from the SD Card. You cannot read data from any other place in a Firefox OS app.

Categories

Resources