Sourcing a local JSON file in JS - javascript

I am creating a weather based artwork-change to be hosted on a local machine with the JSON file updating through an FTP sync. This means that the JSON file will be sourced locally on the same computer. Below is my current code for sourcing the JSON externally. Could you help me with sourcing this locally. Would I just change the URL to the file pathway of where it will be sitting? and remove the GET and send parts.
var xhr = new XMLHttpRequest();
var URL = "http://api.openweathermap.org/data/2.5/weather?q= {London}&appid=genericAPIpassword";
xhr.open("GET", URL, false);
xhr.send();
var weatherResponseStringify = JSON.stringify(xhr.responseText, "", 2);
var weatherResponseParse = JSON.parse(xhr.responseText);
Thank you all for helping!

var myInternalSource = {
key:value,
key:value
}
No need to overcomplicate things. If the json is in another file, then do:
<script src="externalFile.js" ></script>
Or use System.JS Import if you need asychronisity.

Related

How can I change JSON file with javascript

I want to change my JSON file or add an element to my SON file, but real file. I tried this code, but it doesn't work on the real file. Only the time the tab is open on the web has changed. How to handle it in real file? Not user file, it is server file, but I tried my local.
let xmlreq = new XMLHttpRequest()
xmlreq.open("GET","users.json",true)
function test(){
const obj = JSON.parse(xmlreq.responseText);
console.log(obj);
obj.user1.name="john";
console.log('obj.user1.name: ', obj.user1.name);
obj.user2.push("item");
console.log('obj.user2.: ', obj.user2);
}
xmlreq.send()
another
let xmlreq = new XMLHttpRequest()
function test(){
// let parsereq= JSON.parse(xmlreq.responseText);
const obj = JSON.parse(xmlreq.responseText);
console.log(obj);
obj.user1.name="john";
console.log('obj.user1.name: ', obj.user1.name);
obj.user2.push("item");
console.log('obj.user2.: ', obj.user2);
}
xmlreq.open("GET","users.json",true)
xmlreq.send()
First you have to use the File API to load the file.
https://developer.mozilla.org/en-US/docs/Web/API/File
Then you have to parse the JSON data.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse
Then you can do your modifications.
But you can not modify files on your local disc directly. Instead you have to download the file in order to overwrite the original file.
To do so you have to create a data URL from your JSON data.
https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs
And finally you can create a link to download the new JSON.
https://stackoverflow.com/a/15832662/402322

Save a JSON file to server with javascript application

I'm developing a simple Javascript application where the user has some images (stored in my machine) and he is able to annotate them and then save the annotations as a JSON file.
The application is very light and simple and it is not an app server.
However, I need to save those JSON files to the machine that will be behaving as the server.
Since I cannot use Javascript for IO, is there any easy and simple way to save those files without having to implement an app server?
I used Blob to download the files.
function project_save_confirmed(input) {
if ( input.project_name.value !== _onco_settings.project.name ) {
project_set_name(input.project_name.value);
}
// onco project
var _onco_project = { '_onco_settings': _onco_settings,
'_onco_img_metadata': _onco_img_metadata,
'_onco_attributes': _onco_attributes };
var filename = input.project_name.value + '.json';
var data_blob = new Blob( [JSON.stringify(_onco_project)],
{type: 'text/json;charset=utf-8'});
save_data_to_local_file(data_blob, filename);
user_input_default_cancel_handler();
}
function save_data_to_local_file(data, filename) {
var a = document.createElement('a');
a.href = URL.createObjectURL(data);
a.download = filename;
a.click();
}
Any suggestion?
Kind regards!
Copy paste from: Download JSON object as a file from browser
function downloadObjectAsJson(exportObj, exportName){
var dataStr = "data:text/json;charset=utf-8," + encodeURIComponent(JSON.stringify(exportObj));
var downloadAnchorNode = document.createElement('a');
downloadAnchorNode.setAttribute("href", dataStr);
downloadAnchorNode.setAttribute("download", exportName + ".json");
document.body.appendChild(downloadAnchorNode); // required for firefox
downloadAnchorNode.click();
downloadAnchorNode.remove();
}
This I believe accomplishes what you want, just makes sure that the proper headers are set, push it to an <a> tag, then click() it
You can do this in php:
<?php
//notice this will put WHATEVER is in json into file
$filename="config.json";
if (isset($_POST["json"])) {
file_put_contents($filename,$_POST["json"]);
}
?>
then for the JS side:
var fd=new FormData();
fd.append("json", JSON.stringify(_onco_project));
fetch("https://url.com",{method:"POST",body:fd})
Explanation: JS makes a new formdata, and sets "json" to the stringified json, and sends it off to the server. The php server takes this, and puts it directly into $filename. Make sure data is safe before putting it to file, as it will take whatever it is given and put it into your file!

Fetch json data from local using pure Javascript Ajax

So I know this is so lame to ask this question as I have spent a day searching on this subject without any success. As many others, I'm facing the crossdomain problem. The suggestion I see everywhere is to update the JSON file on a server or use localhost which I can't use because my assignment is not allowed to do so.
I am posting this question hoping there is some other solution for this.
I need to fetch data from a JSON file locally using pure JavasSript and Ajax which does not involve hosting on a server nor localhost (using absolute path is also a bad idea).
This is my code so far:
function loadJSON(callback) {
var xobj = new XMLHttpRequest();
xobj.overrideMimeType("application/json");
xobj.open('GET', '/json/userinfo.json', true);
xobj.onreadystatechange = function () {
if (xobj.readyState == 4 && xobj.status == "200") {
callback(xobj.responseText);
}
};
xobj.send(null);
}
(function() {
loadJSON(function(response){
var actual_JSON = JSON.parse(response);
console.log(actual_JSON);
})
})()
You won't be able to access local files using AJAX/XHR. Its not designed for this purpose.
What you can do is assign your json data into a variable in the json file,
var data = [{
}];
and then load your json file using script tag like below:
<script type="text/javascript" src="file_name.json"></script>
Now all the json data can be accessed using the data variable.

Dynamically create list items from local xml file

I'm trying to create a menu from an XML file. The HTML file that I want to create the menu in, is located my main project folder. This folder also contains an xml folder in which my xml file (fruitDB.xml) is located. I understood that there are several ways of loading XML files and that some ways only work online. Eventually the menu is used for an HTML5 mobile app (don't know if this is usefull information), build using Appcelerator.
I've read some sources but it's still not clear to me how I can load an XML file. I have the following code in my header tag:
<script type="text/javascript">
function init(){
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "xml/fruitDB.xml", false);
xmlhttp.setRequestHeader('Content-Type', 'text/xml');
xmlhttp.send();
var xmlDoc = xmlhttp.responseXML;
var Fruits = xmlDoc[];
alert(Fruits);
for (var i = 0; i < Fruits.children.length; i++) {
alert("hi");
var Fruit = Fruits.children[i];
var Name = Fruits.getElementsByTagName("name");
var Thumb = Fruits.getElementsByTagName("image");
var list = document.getElementById("menuButtons");
var listEntry = document.createElement("LI");
listEntry.document.createTextNode(Name);
list.appendChild(listEntry);
}
}
</script>
What I try to do here is open the init(); function using , load the xml file, though I'm not sure if giving a path (like I'm doing) is correct. After the XML is loaded it should create new 's in my HTML file and give them name (and eventually an image) which are stored in the xml file until all items from the xml are placed as list items. Sorry for the long sentence :P.
At xmlhttp.send(); I recieved the following error in my console:
XMLHttpRequest cannot load file:///D:/folder/folder/folder/xml/fruitDB.xml. Received an invalid response. Origin 'null' is therefore not allowed access.
Does this mean that using XMLHttpRequest won't work on local files and if not what other way can I use in order to achieve my goal?
XML doesn't have great support in Titanium. Also XML is often a pain to work with..
Why not use a JSON payload / document instead!
Format the JSON so it is an array of fruit objects
Then you just parse the payload into a javascript object that comes back from the web-service or your local file something like this:
var fruits = JSON.parse(yourHTTPObj.responseData);
Now you can loop over the fruit objects and say:
if (fruits[i].type === 'Apple') { //do something };

javascript xpcom component to download weather underground weather data

I am building a javascript component for Firefox that will take in a zip code, and will return the current weather conditions.
The sample code that weather underground uses jQuery, but as I understand it, I cannot include this code in my javascript component, as javascript does not have the functionality to include other javascript files.
At any rate, I have built up my skeleton code. It takes in the zip code and builds up the url
(example: http://api.wunderground.com/api/e17115d7e24a448e/geolookup/conditions/q/22203.json)
I have tried downloading the data from that url, via the following method:
getWeatherByUrl: function(url)
{
var persist = Components.classes["#mozilla.org/embedding/browser/nsWebBrowserPersist;1"].createInstance(Components.interfaces.nsIWebBrowserPersist);
var file = Components.classes["#mozilla.org/file/directory_service;1"].getService(Components.interfaces.nsIProperties).get("ProfD",Components.interfaces.nsILocalFile);
file.append("weather-forecaster.dat");
var urlURI = Components.classes["#mozilla.org/network/io-service;1"].getService(Components.interfaces.nsIIOService).newURI(url, null, null);
persist.saveURI(urlURI,null,null,null,"",file);
return url;
}
This should download the file to the user's profile directory. It indeed does create the file there. However, it does not look like it contains the json data from weather underground.
What exactly is going on? How would I download the file? I believe that there is a query going on when that url is passed to weather underground, but that shouldn't matter as the .json page is what gets spit out from them, right?
Is there a way to do this without downloading the file, but by streaming it and parsing it?
You can simply use XMLHttpRequest to download this data:
var request = Components.classes["#mozilla.org/xmlextras/xmlhttprequest;1"]
.createInstance(Components.interfaces.nsIXMLHttpRequest);
request.open("GET", "http://api.wunderground.com/api/Your_Key/geolookup/conditions/q/IA/Cedar_Rapids.json");
request.addEventListener("load", function(event)
{
var data = JSON.parse(request.responseText);
alert(data.response.version);
}, false);
request.send(null);

Categories