parsing an external json file in javascript - javascript

I am trying to parse an external JSON file, and then parse it in javascript but i am getting an uncaught reference error.
I first declare the .json file in my html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="style.css">
<script src="script.js"></script>
<script type="text/javascript" src="OnebusinessDataFormat_yelp.json"></script>
<title>title</title>
</head>
<body>
<div class="dropdown">
<button onclick="myFunction()" class="dropbtn">Dropdown</button>
<div id="myDropdown" class="dropdown-content">
<a onclick="name()">NAME</a>
<a onclick="address()">ADDRESS</a>
<a onclick="bh()">BUSINESS HOURS</a>
<a onclick="menu()">MENU</a>
<a onclick="saf()">SERVICES and FEATURES</a>
</div>
</div>
<div id="name">
<p id="rest_name"></p>
</div>
</body>
</html>
I then try to parse that file in my javascript code:
var jsonFile = JSON.parse(OnebusinessDataFormat_yelp.json);
function name(){
document.getElementById("rest_name").innerHTML = jsonFile.name;
}
but when i select name from the dropdown it does not populate the <p> element with the restaurant name.

You need to use the Fetch API in vanilla JS if you want to get the contents of a file:
var jsonFile;
fetch("JOnebusinessDataFormat_yelp.json")
.then(res => res.json())
.then(data => jsonFile = JSON.parse(data));
Please also note that this line:
<script type="text/javascript" src="OnebusinessDataFormat_yelp.json"></script>
Will not work because you can't have a JSON file inside a <script> tag - JSON is JavaScript Object Notation (a string), and is a way of storing JavaScript objects in a simpler way than objects. You can only have a .js file inside a <script> tag.

you can use this code to get the local json file in javascript.
use this url for more reference. $.getJSON Reference
$.getJSON("test.json", function(json) {
console.log(json); // this will show the info it in console
});

I will explain to you how it work, hope it will help you think.
There are 2 types of JavaScript, Server and Client.
If your JavaScript is running on Node.js (Server), all you nee is require().
const json = require(jsonFilePath);
require() will automatically parse the JSON (.json extension file) and generate JavaScript Object for you.
If your JavaScript is running in a Browser (Client), you can't open files from user file system. Just Imagine if Javascript can open any file it want from user file system. All of our data will be in Facebook data center Description 😂.
So for obvious security reasons, you will not be able (as browser app) to open any file you want from the user file system. But you will be able to open files provided by the user like <input type="file" /> or create by yourself in specific way, other people already answered it, you can choose any solution that make sense to your app.

Use this
function loadJSON(callback) {
var xobj = new XMLHttpRequest();
xobj.overrideMimeType("application/json");
xobj.open('GET', 'OnebusinessDataFormat_yelp.json', true);
xobj.onreadystatechange = function () {
if (xobj.readyState == 4 && xobj.status == "200") {
// Required use of an anonymous callback as .open will NOT return a value but simply returns undefined in asynchronous mode
callback(xobj.responseText);
}
};
xobj.send(null);
}
The function above will create a new instance of a XMLHttpRequest and load asynchronously the contents of OnebusinessDataFormat_yelp.json. I have gone with asynchronous but you can change the argument to false if you want a synchronous load. Thankfully all modern browsers support the native JSON.parse method. Remember our anonymous callback? here's how you use it.
function init() {
loadJSON(function(response) {
// Parse JSON string into object
var actual_JSON = JSON.parse(response);
});
}
For more details refer - https://codepen.io/KryptoniteDove/post/load-json-file-locally-using-pure-javascript

Related

Send a variable from a python file, to javascript, and then to a separate HTML file?

I'm trying to create a chrome extension, with the main code being in python but I'm struggling. I've succeeded in sending information from the user inputted from the HTML side to the python script, but not the other way around. Here's what I have so far (or the code that seems to be the problem):
Python:
#app.route('/get_data', methods = ['POST'])
def get_data():
taken = request.get_data()
taken2 = taken.decode()
print(taken2)
strength = int(taken2) #this works, I use this later in the code
my_variable = 5 #just for example
return jsonify(my_variable), 200
background.js (javascript)
function myAction(input) {
console.log("input value is : " + input.value);
newish = input.value
var xxhttp = new XMLHttpRequest();
xxhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
console.log(this.responseText);
}
};
xxhttp.open("POST", "http://127.0.0.1:5000/get_data");
xxhttp.send(newish);
//so sending newish here works, this shows up on my python console (strength becomes this)
HTML
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="button.css">
<script src="background.js" type="text/javascript">
</script>
</head>
<body>
<h1>A Thing!</h1>
<div style="padding: 20px 20px 20px 20px;">
<h3>Hello,</h3>
<p>User input please? : </p>
<input id="name_textbox" />
<button id="ok_btn" type="button">OK</button>
</div>
</body>
</html> stuff
What I'm aiming for is for the my_variable to be accepted into the javascript file somehow, and then the html being able to access and display the contents of my_variable. I've tried looking around, but nowhere seems to have the exact thing I'm looking for (send python variable to separate html file for chrome extension). I'm at a bit of a loss, any help would be greatly appreciated, thanks!
Better way of doing it
Since you want to send the variable from python to html by reading the file, this is better than using the FS module in javascript.
example index.html code:
<body>
<h1>Hello, {first_header:}!</h1>
<p>{p2:}, {p1:}</p>
</body>
python code for the above:
newFileCode = open("index.html", "r").read().format(first_header='goodbye',
p1='World',
p2='Hello')
open("index.html", "w").write(newFileCode)
output in the HTML file:
<body>
<h1>Hello, goodbye!</h1>
<p>Hello, World</p>
</body>
read more about file handling in python here
PREVIOUS ANSWER
You can parse the data using JSON. Although, you'll need a new Node.js module fs https://nodejs.org/api/fs.html.
Once you've installed that module, you have to maintain two JSONs, one being a JS variable and the other being an external .json file.
Use this code to write in external JSON files in javascript:
fs = require('fs');
var name = 'fileName.json';
var m = {"example": "HELLO"}
fs.writeFileSync(name, JSON.stringify(m));
Use this code to read an external JSON file in javascript:
JSON.parse(fs.readFileSync(name).toString())
To get/read the data from the external JSON file in python use this code:
import json
# Opening JSON file
f = open('fileName.json',)
# returns JSON object as
# a dictionary
data = json.load(f)
# Iterating through the json
# list
for i in data['emp_details']:
print(i)
# Closing file
f.close()
You can edit the file from javascript and can read it in python using a while loop

How to set a Dynamics CRM/365 field with Base64String value in JavaScript

I want to set the "base64string" with the base 64 string value of a document, then I will later take that value and load the document onto sharepoint(I already have the c# code for this working through a console application).
My code below does not seem to work, basically the value is never set, The field base64string is a multi-line with 1 million characters.
<html>
<head>
<meta charset="utf-8">
</head>
<body>
Please select a file and then hit Evaluate:
<br/>
<input id="file" type="file" />
<button id="button">Upload
<script>
document.getElementById('button').addEventListener('click', function() {
var files = document.getElementById('file').files;
if (files.length > 0) {
getBase64(files[0]);
}
});
function getBase64(file) {
var reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function () {
Xrm.Page.getAttribute("base64string").setValue(reader.result);
};
reader.onerror = function (error) {};
}
</script>
</body>
</html>
In Xrm.Page.getAttribute("base64string"), are you certain base64string is a field name? If its a custom field it should have a prefix such as abc_base64string.
Furthermore a HTML web resouce can't directly access Xrm.Page.
Reference other web resources from an HTML web resource.
An HTML web resource added to a form can’t use global objects defined
by the JavaScript library loaded in the form. An HTML web resource may
interact with the Xrm.Page or Xrm.Utility objects within the form by
using parent.Xrm.Page or parent.Xrm.Utility, but global objects
defined by form scripts won’t be accessible using the parent.
I belive your code should look more like this:
reader.onload = function () {
parent.Xrm.Page.getAttribute("abc_base64string").setValue(reader.result);
};

How to make a JQuery routine write to a text file on a computer desktop?

I want to make a JQuery routine that can write information (append) to a text file that either exists or does not exists. If the file does not exists than it should create the file and if it does it should either append or start writing new data to the file. I think append would be the best choice for a file logger. So it must append the data to the file.
I found this code on the internet and am trying to work it around so that I can use it on my page to write information to a simple text file.
Question: How can I make the following code log to a file for download?
Below is the new code and how I read the page that was listed in the comments on how a logger in Java script should work. The code is not working and I am not really certain as to why.
I am not really certain as to how the download works either but if I can just get the logger to work I will be happy for the time being.
Code:
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js">
<script src="log4moz.js">
</head>
<script>
getLocalDirectory : function() {
let directoryService = Cc["#mozilla.org/file/directory_service;1"].getService(Ci.nsIProperties);
// this is a reference to the profile dir (ProfD) now.
let localDir = directoryService.get("ProfD", Ci.nsIFile);
localDir.append("XULSchool");
if (!localDir.exists() || !localDir.isDirectory()) {
// read and write permissions to owner and group, read-only for others.
localDir.create(Ci.nsIFile.DIRECTORY_TYPE, 0774);
}
return localDir;
}
let myFile = XULSchool.getLocalDirectory();
myFile.append("someFile.txt");
let formatter = new Log4Moz.BasicFormatter();
let root = Log4Moz.repository.rootLogger;
let logFile = this.getLocalDirectory(); // remember this?
let appender;
logFile.append("log.txt");
root.level = Log4Moz.Level["All"];
appender = new Log4Moz.RotatingFileAppender(logFile, formatter);
appender.level = Log4Moz.Level["All"];
root.addAppender(appender);
this._logger = Log4Moz.repository.getLogger("XULSchool.SomeObject");
this._logger.level = Log4Moz.Level["All"];
this._logger.fatal("This is a fatal message.");
this._logger.error("This is an error message.");
this._logger.warn("This is a warning message.");
this._logger.info("This is an info message.");
this._logger.config("This is a config message.");
this._logger.debug("This is a debug message.");
this._logger.trace("This is a trace message.");
</script>
<body>
<form id="addnew">
<input type="text" class="A">
<input type="text" class="B">
<input type="submit" value="Add">
</form>
</body>
</html>
#Smeegs says this nicely
Imagine a world where any website can edit files on your computer
JavaScript (or jQuery) cannot touch the user's file system.
Even if you find some hacked up thing that works via ActiveXObject, you should not attempt to do this. Cross-browser support would be very narrow for this feature.
If you want to write out file, just provide the user with a download.
If this is just a means of reading/writing some kind of data, look into localstorage.

What is the equivalent of wget in javascript to download a file from a given url?

"wget http://www.example.com/file.doc" downloads that file to the local disk.
What is the equivalent of the above in javascript? for example, consider the following html snippet.
<html>
<head>
<script language="JavaScript">
function download_file() {
var url = "http://www.example.com/file.doc"
//
// Question:
//
// what should be done here to download
// the file in the url?
//
}
</script>
</head>
<body>
<input type="button" value="Download" onclick="download_file()">
</body>
</html>
Please suggest a solution that is compliant with all the browsers.
Sangeeth.
After a exploring more than a month, with a help of my friend, we were able to find out the following.
The website where the file is hosted is not allowing us to download the file using window.location = url; or window.open(url);
Finally we had to use the data-downloadurl support from HTML5 as follows
Click here to download the file
We embed this html into the host html and when clicked on the link, it triggers the download.
Why not use:
function download_file() {
var url = "http://www.example.com/file.doc"
window.location = url;
}
See https://developer.mozilla.org/en/DOM/window.location
If you need to open this in a new window/tab first then use:
function download_file() {
var url = "http://www.example.com/file.doc"
window.open(url);
}
See https://developer.mozilla.org/en/DOM/window.open
First thing that always comes in mind of every answerer to this question is executing wget shell command from java script.I'm almost certain that that's not possible because of
major security risk.
You pretty much need to have ajax which sends command to command line
either through php, or another scripting language via ajax...
You could probably make that happen with something like http://www.phantomjs.org/
I am saying probably because I read it from somewhere.

Create File with Javascript

is it possible to create a file on localhost with javascript?
Not in a webpage. If you're using Windows Script Host then yes you can through ActiveX, but I presume you're not doing that. You can however, send data back to the webserver through AJAX and have it store it for you.
You can create cookies to store data on the local machine, which pretty much is the only way to create files on the local machine.
I assume you have the content of the file ready. Then you can prompt a "save as" dialog like this:
var exportText; // this variable needs to contain your content
var targetFilename = "myfilename.ext"
function presentExportFile() {
var download = document.createElement('a');
// you need to change the contenttype to your needs in the next line.
download.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(exportText));
download.setAttribute('download', targetFilename);
download.style.display = 'none';
document.body.appendChild(download);
download.click();
document.body.removeChild(download);
}
2017 addendum: Since I wrote this, I had one exotic browser (xombrero) reject it. So, I can't say for certain that this is The Way.
no, this would be a security issue.
You can create a file through a plugin, see https://developer.mozilla.org/en/Code_snippets/File_I%2F%2FO
<html>
<head>
<title>Create File</title>
<! This function will create a file named 'newfile' on the same directory as the HTML unless path is given>
<script language="javascript">
function openFile()
{ var filePath = 'c:/filename.txt';
var fileSysObj = new ActiveXObject('Scripting.FileSystemObject');
fileSysObj.CreateTextFile(filePath);
}
</script>
</head>
<body>
This will create a file called "filename.txt" on your c:\ drive.
You must accept the ActiveX control or disable prompting to create a file.
<button type=submit name=button onClick="openFile();">create file</button>
</body>
</html>

Categories

Resources