async line-by-line file reading - javascript

When I try to read a file synchronously, Firefox freezes.
When I try to read a file asynchronously, I get numbers instead of words.
This code snippet...
var MY_ID = "cbdeltrem1984#bol.com.br";
var em = Components.classes["#mozilla.org/extensions/manager;1"].getService(Components.interfaces.nsIExtensionManager);
var file = em.getInstallLocation(MY_ID).getItemFile(MY_ID, "wordlist.txt");
...plus this code snippet...
var appInfo=Components.classes["#mozilla.org/xre/app-info;1"].getService(Components.interfaces.nsIXULAppInfo);
var isOnBranch = appInfo.platformVersion.indexOf("1.8") == 0;
var ios=Components.classes["#mozilla.org/network/io-service;1"].getService(Components.interfaces.nsIIOService);
var fileURI=ios.newFileURI(file);
var channel = ios.newChannelFromURI(fileURI);
var observer = {
onStreamComplete : function(aLoader, aContext, aStatus, aLength, aResult) {
alert(aResult);
}
};
var sl = Components.classes["#mozilla.org/network/stream-loader;1"].createInstance(Components.interfaces.nsIStreamLoader);
if (isOnBranch) {
sl.init(channel, observer, null);
} else {
sl.init(observer);
channel.asyncOpen(sl, channel);
}
...alerts numbers instead of words.
How to read a file asynchronously line-by-line?

The below sample can read files asynchronously, without locking UI thread (works with FF4+ only though, since I used Modules). Doesn't read line-by-line... Also, I assumed it to be text file, though..
Components.utils.import("resource://gre/modules/NetUtil.jsm");
NetUtil.asyncFetch(file, function(inputStream, status) {
if (!Components.isSuccessCode(status)) {
// Handle error!
return;
}
// The file data is contained within inputStream.
// You can read it into a string with
var data = NetUtil.readInputStreamToString(inputStream, inputStream.available());
Components.utils.reportError("data:" + data);
});
Sources:
https://developer.mozilla.org/en/JavaScript_code_modules/NetUtil.jsm
https://developer.mozilla.org/en/Code_snippets/File_I%2F%2FO#Read_into_a_stream_or_a_string

Related

Using MP4box.js and onSegment callback is not called

Base problem: display a H264 live stream in a browser.
Solution: let's just convert it to fragmented mp4 and load chunk-by-chunk via websocket (or XHR) into MSE.
Sounds too easy. But I want to do the fragmentation on client side with pure JS.
So I'm trying to use MP4Box.js. On its readme page it states: it has a demo: "A player that performs on-the-fly fragmentation".
That's the thing I need!
However the onSegment callbacks which should feed MSE are not called at all:
var ws; //for websocket
var mp4box; //for fragmentation
function startVideo() {
mp4box = MP4Box.createFile();
mp4box.onError = function(e) {
console.log("mp4box failed to parse data.");
};
mp4box.onMoovStart = function () {
console.log("Starting to receive File Information");
};
mp4box.onReady = function(info) {
console.log(info.mime);
mp4box.onSegment = function (id, user, buffer, sampleNum) {
console.log("Received segment on track "+id+" for object "+user+" with a length of "+buffer.byteLength+",sampleNum="+sampleNum);
}
var options = { nbSamples: 1000 };
mp4box.setSegmentOptions(info.tracks[0].id, null, options); // I don't need user object this time
var initSegs = mp4box.initializeSegmentation();
mp4box.start();
};
ws = new WebSocket("ws://a_websocket_server_which_serves_h264_file");
ws.binaryType = "arraybuffer";
ws.onmessage = function (event) {
event.data.fileStart = 0; //tried also with event.data.byteOffset, but resulted error.
var nextBufferStart = mp4box.appendBuffer(event.data);
mp4box.flush(); //tried commenting out - unclear documentation!
};
}
window.onload = function() {
startVideo();
}
Now putting this into an HTML file would result this in the JavaScript console:
Starting to receive File Information
video/mp4; codecs="avc1.4d4028"; profiles="isom,iso2,avc1,iso6,mp41"
But nothing happens afterwards. Why is the onSegment not called here? (the h264 file which the websocket-server serves is playable in VLC - however it is not fragmented)
The problem was using the nextBufferStart in a wrong way.
This should be the correct one:
var nextBufferStart = 0;
...
ws.onmessage = function (event) {
event.data.fileStart = nextBufferStart;
nextBufferStart = mp4box.appendBuffer(event.data);
mp4box.flush();
};

How to get objects from txt file to use in javascript array?

I am very new to coding and javascript; just a few days in. I was wondering if there was a way to import objects from a text file(separated by lines) to use in my array: replyText. Here is what I'm working with:
// Variables
var theButton = document.getElementById("theButton");
var mainText = document.getElementById("mainText");
var replyText = [...,...,...,...,];
var i = 0;
// Functions
function nextText() {
mainText.innerHTML = replyText[i++ % replyText.length];
}
// MAIN SCRIPT
theButton.onclick = function() {
nextText();
};
You can use XMLHttpRequest to get the .txt file just pass the path of it.
var file = new XMLHttpRequest();
file.open("GET", "file:/../file.txt", false);
file.onreadystatechange = function () {
if (file.readyState === 4) {
if (file.status === 200 || file.status == 0) {
var text = file.responseText;
alert(text);
}
}
}
EDIT: you must pass the absolute path file:///C:/your/path/to/file.txt
For client/browser-side file reading:
You cannot easily read a file on the client-side as you are not allowed direct access to the client's file system. However, you can place a input element of file type in your HTML markup via which the client can load a file for your program to process. For example:
<input type="file" id="file" onchange="readFile()" />
Now when the client selects a file for use, the readFile() function will be called which will read and process the file. Here's an example:
function readFile() {
var file = document.getElementById('file').files[0]; // select the input element from the DOM
var fileReader = new FileReader(); // initialize a new File Reader object
fileReader.onload(function() { // call this function when file is loaded
console.log(this.result); // <--- You can access the file data from this variable
// Do necessary processing on the file
});
fileReader.readAsText(file); // Read the file as text
}
For more information on File Reader, check out the docs.
To add on to Paulo's solution, read below for splitting string by line breaks (new line character)
var replyText = text.split("\n"); // "\n" is new line character

document generation only works the first time

I'm using openxml in my HTML5 mobile app to generate word documents on the mobile device.
In general openxml works fine and straight forward, but I'm struggling with an annyoing problem.
The document generation only works the first time after I've started the app. This time I can open and view the document. Restart the app means:
- Redeploy from development machine
- Removing the app from the task pane (pushing aside; I assume the app is removed then?)
The second time I get the message the document is corrupted and I'm unable to view the file
UPDATE:
I can't reproduce this behaviour when I'm running the app connected to the remote debugger without having a breakpoint set. Doing it this way I always get a working document.
I doesn't make a difference wether I do any changes on the document or not. Simply open and saving reproduce this error.
After doing some research I've found that structure of the docx.zip file of the working and the corrupt file is the same. They also have the same file length. But in the corrupt docx there are some files I've found some files having a wrong/invalid CRC. See here an example when trying to get a corrupt file out of the zip. Other files are working as expected.
The properties for this file are->
(CRC in a working version is: 44D3906C)
Code for processing the doc-template:
/*
* Process the template
*/
function processTemplate(doc64, callback)
{
"use strict";
console.log("PROCESS TEMPLATE");
var XAttribute = Ltxml.XAttribute;
var XCData = Ltxml.XCData;
var XComment = Ltxml.XComment;
var XContainer = Ltxml.XContainer;
var XDeclaration = Ltxml.XDeclaration;
var XDocument = Ltxml.XDocument;
var XElement = Ltxml.XElement;
var XName = Ltxml.XName;
var XNamespace = Ltxml.XNamespace;
var XNode = Ltxml.XNode;
var XObject = Ltxml.XObject;
var XProcessingInstruction = Ltxml.XProcessingInstruction;
var XText = Ltxml.XText;
var XEntity = Ltxml.XEntity;
var cast = Ltxml.cast;
var castInt = Ltxml.castInt;
var W = openXml.W;
var NN = openXml.NoNamespace;
var wNs = openXml.wNs;
var doc = new openXml.OpenXmlPackage(doc64);
// add a paragraph to the beginning of the document.
var body = doc.mainDocumentPart().getXDocument().root.element(W.body);
var tpl_row = ((doc.mainDocumentPart().getXDocument().descendants(W.tbl)).elementAt(1).descendants(W.tr)).elementAt(2);
var newrow = new XElement(tpl_row);
doc.mainDocumentPart().getXDocument().descendants(W.tbl).elementAt(1).add(newrow);
// callback(doc);
var mod_file = null;
var newfile;
var path;
if (doc != null && doc != undefined ) {
mod_file = doc.saveToBlob();
// Start writing document
path = "Templates";
newfile = "Templates/Bau.docx";
console.log("WRITE TEMPLATE DOCUMENT");
fs.root.getFile("Templates/" + "MyGenerated.docx", {create: true, exclusive: false},
function(fileEntry)
{
fileEntry.createWriter(
function(fileWriter)
{
fileWriter.onwriteend = function(e) {
console.log("TEMPLATE DOCUMENT WRITTEN:"+e.target.length);
};
fileWriter.onerror = function(e) {
console.log("ERROR writing DOCUMENT:" + e.code + ";" + e.message);
};
var blobreader = new FileReader();
blobreader.onloadend = function()
{
fileWriter.write(blobreader.result); // reader.result contains the contents of blob as a typed array
};
blobreader.readAsArrayBuffer(mod_file);
},
null);
}, null);
};
Any ideas what I'm doing wrong?
Thanks for posting about the error. There were some issues with jszip.js that I encountered when I was developing the Open XML SDK for JavaScript.
At the following link, there is a sample javascript app that demonstrates generating a document.
Open XML SDK for JavaScript Demo
In that app you can save multiple DOCXs, one after another, and they are not corrupted.
In order to work on this issue, I need to be able to re-produce locally. Maybe you can take that little working web app and replace parts with your parts until it is generating invalid files?
Cheers, Eric
P.S. I am traveling and have intermittent access to internet. If you can continue the thread on OpenXmlDeveloper.org, then it will help me to answer quicker. :-)
What made it work for me, was changing the way of adding images (Parts) to the document. I was using the type "binary" for adding images to document. I changed this to "base64"
So I changed the source from:
mydoc.addPart( "/word/"+reltarget, openXml.contentTypes.png, "binary", fotodata ); // add Image Part to doc
to:
mydoc.addPart( "/word/"+reltarget, openXml.contentTypes.png, "base64", window.btoa(fotodata) ); // add Image Part to doc

How to change emscripten browser input method from window.prompt to something more sensible?

I have a C++ function which once called consumes input from stdin. Exporting this function to javascript using emscripten causes calls to window.prompt.
Interacting with browser prompt is really tedious task. First of all you can paste only one line at time. Secondly the only way to indicate EOF is by pressing 'cancel'. Last but not least the only way (in case of my function) to make it stop asking user for input by window.prompt is by checking the checkbox preventing more prompts to pop up.
For me the best input method would be reading some blob. I know I can hack library.js but I see some problems:
Reading blob is asynchronous.
To read a blob, first you have to open a file user has to select first.
I don't really know how to prevent my function from reading this blob forever - there is no checkbox like with window.prompt and I'm not sure if spotting EOF will stop it if it didn't in window.prompt case (only checking a checkbox helped).
The best solution would be some kind of callback but I would like to see sime hints from more experienced users.
A way would be to use the Emscripten Filesystem API, for example by calling FS.init in the Module preRun function, passing a custom function as the standard input.
var Module = {
preRun: function() {
function stdin() {
// Return ASCII code of character, or null if no input
}
var stdout = null; // Keep as default
var stderr = null; // Keep as default
FS.init(stdin, stdout, stderr);
}
};
The function is quite low-level: is must deal with one character at a time. To read some data from a blob, you could do something like:
var data = new Int8Array([1,2,3,4,5]);
var blob = new Blob([array], {type: 'application/octet-binary'});
var reader = new FileReader();
var result;
reader.addEventListener("loadend", function() {
result = new Int8Array(reader.result);
});
var i = 0;
var Module = {
preRun: function() {
function stdin() {
if (if < result.byteLength {
var code = result[i];
++i;
return code;
} else {
return null;
}
}
var stdout = null; // Keep as default
var stderr = null; // Keep as default
FS.init(stdin, stdout, stderr);
}
};
Note (as you have hinted), due to the asynchronous nature of the reader, there could be a race condition: the reader must have loaded before you can expect the data at the standard input. You might need to implement some mechanism to avoid this in a real case. Depending on your exact requirements, you could make it so the Emscripten program doesn't actually call main() until you have the data:
var fileRead = false;
var initialised = false;
var result;
var array = new Int8Array([1,2,3,4,5]);
var blob = new Blob([array], {type: 'application/octet-binary'});
var reader = new FileReader();
reader.addEventListener("loadend", function() {
result = new Int8Array(reader.result);
fileRead = true;
runIfCan();
});
reader.readAsArrayBuffer(blob);
var i = 0;
var Module = {
preRun: function() {
function stdin() {
if (i < result.byteLength)
{
var code = result[i];
++i;
return code;
} else{
return null;
}
}
var stdout = null;
var stderr = null;
FS.init(stdin, stdout, stderr);
initialised = true;
runIfCan();
},
noInitialRun: true
};
function runIfCan() {
if (fileRead && initialised) {
// Module.run() doesn't seem to work here
Module.callMain();
}
}
Note: this is a version of my answer at Providing stdin to an emscripten HTML program? , but with focus on the standard input, and adding parts about passing data from a Blob.
From what I understand you could try the following:
Implement selecting a file in Javascript and access it via Javascript Blob interface.
Allocate some memory in Emscripten
var buf = Module._malloc( blob.size );
Write the content of your Blob into the returned memory location from Javascript.
Module.HEAPU8.set( new Uint8Array(blob), buf );
Pass that memory location to a second Emscripten compiled function, which then processes the file content and
Deallocate allocated memory.
Module._free( buf );
Best to read the wiki first.

Loading local JSON file

I'm trying to load a local JSON file but it won't work. Here is my JavaScript code (using jQuery):
var json = $.getJSON("test.json");
var data = eval("(" +json.responseText + ")");
document.write(data["a"]);
The test.json file:
{"a" : "b", "c" : "d"}
Nothing is displayed and Firebug tells me that data is undefined. In Firebug I can see json.responseText and it is good and valid, but it's strange when I copy the line:
var data = eval("(" +json.responseText + ")");
in Firebug's console, it works and I can access data.
Does anyone have a solution?
$.getJSON is asynchronous so you should do:
$.getJSON("test.json", function(json) {
console.log(json); // this will show the info it in firebug console
});
I had the same need (to test my angularjs app), and the only way I found is to use require.js:
var json = require('./data.json'); //(with path)
note: the file is loaded once, further calls will use the cache.
More on reading files with nodejs: http://docs.nodejitsu.com/articles/file-system/how-to-read-files-in-nodejs
require.js: http://requirejs.org/
In a more modern way, you can now use the Fetch API:
fetch("test.json")
.then(response => response.json())
.then(json => console.log(json));
All modern browsers support Fetch API. (Internet Explorer doesn't, but Edge does!)
or with async/await
async function printJSON() {
const response = await fetch("test.json");
const json = await response.json();
console.log(json);
}
source:
Using Fetch
Fetch in Action
Can I use...?
How to Use Fetch with async/await
If you want to let the user select the local json file (anywhere on the filesystem), then the following solution works.
It uses FileReader and JSON.parser (and no jquery).
<html>
<body>
<form id="jsonFile" name="jsonFile" enctype="multipart/form-data" method="post">
<fieldset>
<h2>Json File</h2>
<input type='file' id='fileinput'>
<input type='button' id='btnLoad' value='Load' onclick='loadFile();'>
</fieldset>
</form>
<script type="text/javascript">
function loadFile() {
var input, file, fr;
if (typeof window.FileReader !== 'function') {
alert("The file API isn't supported on this browser yet.");
return;
}
input = document.getElementById('fileinput');
if (!input) {
alert("Um, couldn't find the fileinput element.");
}
else if (!input.files) {
alert("This browser doesn't seem to support the `files` property of file inputs.");
}
else if (!input.files[0]) {
alert("Please select a file before clicking 'Load'");
}
else {
file = input.files[0];
fr = new FileReader();
fr.onload = receivedText;
fr.readAsText(file);
}
function receivedText(e) {
let lines = e.target.result;
var newArr = JSON.parse(lines);
}
}
</script>
</body>
</html>
Here is a good intro on FileReader: http://www.html5rocks.com/en/tutorials/file/dndfiles/
If you're looking for something quick and dirty just load the data in the head of your HTML document.
data.js
var DATA = {"a" : "b", "c" : "d"};
index.html
<html>
<head>
<script src="data.js" ></script>
<script src="main.js" ></script>
</head>
...
</html>
main.js
(function(){
console.log(DATA); // {"a" : "b", "c" : "d"}
})();
I should mention that your heap size (in Chrome) is about 4GBs, so if your data is larger than that you should find another method. If you want to check another browser try this:
window.performance.memory.jsHeapSizeLimit / 1024 / 1024 / 1024 + " GBs"
// "4.046875 GBs"
Update ES6:
Instead of using the <script> tag to load your data you can load it directly inside you're main.js using the import assert
import data from './data.json' assert {type: 'json'};
how to using XMLHttpRequest to load the local json file
ES5 version
// required use of an anonymous callback,
// as .open() will NOT return a value but simply returns undefined in asynchronous mode!
function loadJSON(callback) {
var xObj = new XMLHttpRequest();
xObj.overrideMimeType("application/json");
xObj.open('GET', './data.json', true);
// 1. replace './data.json' with the local path of your file
xObj.onreadystatechange = function() {
if (xObj.readyState === 4 && xObj.status === 200) {
// 2. call your callback function
callback(xObj.responseText);
}
};
xObj.send(null);
}
function init() {
loadJSON(function(response) {
// 3. parse JSON string into JSON Object
console.log('response =', response);
var json = JSON.parse(response);
console.log('your local JSON =', JSON.stringify(json, null, 4));
// 4. render to your page
const app = document.querySelector('#app');
app.innerHTML = '<pre>' + JSON.stringify(json, null, 4) + '</pre>';
});
}
init();
<section id="app">
loading...
</section>
ES6 version
// required use of an anonymous callback,
// as .open() will NOT return a value but simply returns undefined in asynchronous mode!
const loadJSON = (callback) => {
const xObj = new XMLHttpRequest();
xObj.overrideMimeType("application/json");
// 1. replace './data.json' with the local path of your file
xObj.open('GET', './data.json', true);
xObj.onreadystatechange = () => {
if (xObj.readyState === 4 && xObj.status === 200) {
// 2. call your callback function
callback(xObj.responseText);
}
};
xObj.send(null);
}
const init = () => {
loadJSON((response) => {
// 3. parse JSON string into JSON Object
console.log('response =', response);
const json = JSON.parse(response);
console.log('your local JSON =', JSON.stringify(json, null, 4));
// 4. render to your page
const app = document.querySelector('#app');
app.innerHTML = `<pre>${JSON.stringify(json, null, 4)}</pre>`;
});
}
init();
<section id="app">
loading...
</section>
online demo
https://cdn.xgqfrms.xyz/ajax/XMLHttpRequest/index.html
I can't believe how many times this question has been answered without understanding and/or addressing the problem with the Original Poster's actual code. That said, I'm a beginner myself (only 2 months of coding). My code does work perfectly, but feel free to suggest any changes to it. Here's the solution:
//include the 'async':false parameter or the object data won't get captured when loading
var json = $.getJSON({'url': "http://spoonertuner.com/projects/test/test.json", 'async': false});
//The next line of code will filter out all the unwanted data from the object.
json = JSON.parse(json.responseText);
//You can now access the json variable's object data like this json.a and json.c
document.write(json.a);
console.log(json);
Here's a shorter way of writing the same code I provided above:
var json = JSON.parse($.getJSON({'url': "http://spoonertuner.com/projects/test/test.json", 'async': false}).responseText);
You can also use $.ajax instead of $.getJSON to write the code exactly the same way:
var json = JSON.parse($.ajax({'url': "http://spoonertuner.com/projects/test/test.json", 'async': false}).responseText);
Finally, the last way to do this is to wrap $.ajax in a function. I can't take credit for this one, but I did modify it a bit. I tested it and it works and produces the same results as my code above. I found this solution here --> load json into variable
var json = function () {
var jsonTemp = null;
$.ajax({
'async': false,
'url': "http://spoonertuner.com/projects/test/test.json",
'success': function (data) {
jsonTemp = data;
}
});
return jsonTemp;
}();
document.write(json.a);
console.log(json);
The test.json file you see in my code above is hosted on my server and contains the same json data object that he (the original poster) had posted.
{
"a" : "b",
"c" : "d"
}
Add to your JSON file from the beginning
var object1 = [
and at the end
]
Save it
Then load it with pure js as
<script type="text/javascript" src="1.json"></script>
And now you can use it as object1 - its already loaded!
Works perfectly in Chrome and without any additional libraries
I'm surprised import from es6 has not been mentioned (use with small files)
Ex: import test from './test.json'
webpack 2< uses the json-loader as default for .json files.
https://webpack.js.org/guides/migrating/#json-loader-is-not-required-anymore
For TypeScript:
import test from 'json-loader!./test.json';
TS2307 (TS) Cannot find module 'json-loader!./suburbs.json'
To get it working I had to declare the module first. I hope this will save a few hours for someone.
declare module "json-loader!*" {
let json: any;
export default json;
}
...
import test from 'json-loader!./test.json';
If I tried to omit loader from json-loader I got the following error from webpack:
BREAKING CHANGE: It's no longer allowed to omit the '-loader' suffix
when using loaders.
You need to specify 'json-loader' instead of 'json',
see https://webpack.js.org/guides/migrating/#automatic-loader-module-name-extension-removed
Recently D3js is able to handle local json file.
This is the issue
https://github.com/mbostock/d3/issues/673
This is the patch inorder for D3 to work with local json files.
https://github.com/mbostock/d3/pull/632
Found this thread when trying (unsuccessfully) to load a local json file. This solution worked for me...
function load_json(src) {
var head = document.getElementsByTagName('head')[0];
//use class, as we can't reference by id
var element = head.getElementsByClassName("json")[0];
try {
element.parentNode.removeChild(element);
} catch (e) {
//
}
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = src;
script.className = "json";
script.async = false;
head.appendChild(script);
//call the postload function after a slight delay to allow the json to load
window.setTimeout(postloadfunction, 100)
}
... and is used like this...
load_json("test2.html.js")
...and this is the <head>...
<head>
<script type="text/javascript" src="test.html.js" class="json"></script>
</head>
What I did was editing the JSON file little bit.
myfile.json => myfile.js
In the JSON file, (make it a JS variable)
{name: "Whatever"} => var x = {name: "Whatever"}
At the end,
export default x;
Then,
import JsonObj from './myfile.js';
In TypeScript you can use import to load local JSON files. For example loading a font.json:
import * as fontJson from '../../public/fonts/font_name.json';
This requires a tsconfig flag --resolveJsonModule:
// tsconfig.json
{
"compilerOptions": {
"module": "commonjs",
"resolveJsonModule": true,
"esModuleInterop": true
}
}
For more information see the release notes of typescript: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-9.html
In angular (or any other framework), you can load using http get
I use it something like this:
this.http.get(<path_to_your_json_file))
.success((data) => console.log(data));
Hope this helps.
An approach I like to use is to pad/wrap the json with an object literal, and then save the file with a .jsonp file extension. This method also leaves your original json file (test.json) unaltered, as you will be working with the new jsonp file (test.jsonp) instead. The name on the wrapper can be anything, but it does need to be the same name as the callback function you use to process the jsonp. I'll use your test.json posted as an example to show the jsonp wrapper addition for the 'test.jsonp' file.
json_callback({"a" : "b", "c" : "d"});
Next, create a reusable variable with global scope in your script to hold the returned JSON. This will make the returned JSON data available to all other functions in your script instead of just the callback function.
var myJSON;
Next comes a simple function to retrieve your json by script injection. Note that we can not use jQuery here to append the script to the document head, as IE does not support the jQuery .append method. The jQuery method commented out in the code below will work on other browsers that do support the .append method. It is included as a reference to show the difference.
function getLocalJSON(json_url){
var json_script = document.createElement('script');
json_script.type = 'text/javascript';
json_script.src = json_url;
json_script.id = 'json_script';
document.getElementsByTagName('head')[0].appendChild(json_script);
// $('head')[0].append(json_script); DOES NOT WORK in IE (.append method not supported)
}
Next is a short and simple callback function (with the same name as the jsonp wrapper) to get the json results data into the global variable.
function json_callback(response){
myJSON = response; // Clone response JSON to myJSON object
$('#json_script').remove(); // Remove json_script from the document
}
The json data can now be accessed by any functions of the script using dot notation. As an example:
console.log(myJSON.a); // Outputs 'b' to console
console.log(myJSON.c); // Outputs 'd' to console
This method may be a bit different from what you are used to seeing, but has many advantages. First, the same jsonp file can be loaded locally or from a server using the same functions. As a bonus, jsonp is already in a cross-domain friendly format and can also be easily used with REST type API's.
Granted, there are no error handling functions, but why would you need one? If you are unable to get the json data using this method, then you can pretty much bet you have some problems within the json itself, and I would check it on a good JSON validator.
You can put your json in a javascript file. This can be loaded locally (even in Chrome) using jQuery's getScript() function.
map-01.js file:
var json = '{"layers":6, "worldWidth":500, "worldHeight":400}'
main.js
$.getScript('map-01.js')
.done(function (script, textStatus) {
var map = JSON.parse(json); //json is declared in the js file
console.log("world width: " + map.worldWidth);
drawMap(map);
})
.fail(function (jqxhr, settings, exception) {
console.log("error loading map: " + exception);
});
output:
world width: 500
Notice that the json variable is declared and assigned in the js file.
$.ajax({
url: "Scripts/testingJSON.json",
//force to handle it as text
dataType: "text",
success: function (dataTest) {
//data downloaded so we call parseJSON function
//and pass downloaded data
var json = $.parseJSON(dataTest);
//now json variable contains data in json format
//let's display a few items
$.each(json, function (i, jsonObjectList) {
for (var index = 0; index < jsonObjectList.listValue_.length;index++) {
alert(jsonObjectList.listKey_[index][0] + " -- " + jsonObjectList.listValue_[index].description_);
}
});
}
});
If you are using a local array for JSON - as you showed in your example in the question (test.json) then you can is the parseJSON() method of JQuery ->
var obj = jQuery.parseJSON('{"name":"John"}');
alert( obj.name === "John" );
getJSON() is used for getting JSON from a remote site - it will not work locally (unless you are using a local HTTP Server)
How I was able to load the data from a json file in to a JavaScript variable using simple JavaScript:
let mydata;
fetch('datafile.json')
.then(response => response.json())
.then(jsonResponse => mydata = jsonResponse)
Posting here as I didn't find this kind of "solution" I was looking for.
Note: I am using a local server run via the usual "python -m http.server" command.
$.getJSON only worked for me in Chrome 105.0.5195.125 using await, which works a script type of module.
<script type="module">
const myObject = await $.getJSON('./myObject.json');
console.log('myObject: ' + myObject);
</script>
Without await, I see:
Uncaught TypeError: myObject is not iterable
when resolving myObject.
Without type="module" I see:
Uncaught SyntaxError: await is only valid in async functions and the top level bodies of modules
I haven't found any solution using Google's Closure library. So just to complete the list for future vistors, here's how you load a JSON from local file with Closure library:
goog.net.XhrIo.send('../appData.json', function(evt) {
var xhr = evt.target;
var obj = xhr.getResponseJson(); //JSON parsed as Javascript object
console.log(obj);
});
json_str = String.raw`[{"name": "Jeeva"}, {"name": "Kumar"}]`;
obj = JSON.parse(json_str);
console.log(obj[0]["name"]);
I did this for my cordova app, like I created a new javascript file for the JSON and pasted the JSON data into String.raw then parse it with JSON.parse
function readTextFile(srcfile) {
try { //this is for IE
var fso = new ActiveXObject("Scripting.FileSystemObject");;
if (fso.FileExists(srcfile)) {
var fileReader = fso.OpenTextFile(srcfile, 1);
var line = fileReader.ReadLine();
var jsonOutput = JSON.parse(line);
}
} catch (e) {
}
}
readTextFile("C:\\Users\\someuser\\json.txt");
What I did was, first of all, from network tab, record the network traffic for the service, and from response body, copy and save the json object in a local file. Then call the function with the local file name, you should be able to see the json object in jsonOutout above.
What worked for me is the following:
Input:
http://ip_address//some_folder_name//render_output.html?relative/path/to/json/fie.json
Javascript Code:
<html>
<head>
<style>
pre {}
.string { color: green; }
.number { color: darkorange; }
.boolean { color: blue; }
.null { color: magenta; }
.key { color: red; }
</style>
<script>
function output(inp) {
document.body.appendChild(document.createElement('pre')).innerHTML = inp;
}
function gethtmlcontents(){
path = window.location.search.substr(1)
var rawFile = new XMLHttpRequest();
var my_file = rawFile.open("GET", path, true) // Synchronous File Read
//alert('Starting to read text')
rawFile.onreadystatechange = function ()
{
//alert("I am here");
if(rawFile.readyState === 4)
{
if(rawFile.status === 200 || rawFile.status == 0)
{
var allText = rawFile.responseText;
//alert(allText)
var json_format = JSON.stringify(JSON.parse(allText), null, 8)
//output(json_format)
output(syntaxHighlight(json_format));
}
}
}
rawFile.send(null);
}
function syntaxHighlight(json) {
json = json.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
return json.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, function (match) {
var cls = 'number';
if (/^"/.test(match)) {
if (/:$/.test(match)) {
cls = 'key';
} else {
cls = 'string';
}
} else if (/true|false/.test(match)) {
cls = 'boolean';
} else if (/null/.test(match)) {
cls = 'null';
}
return '<span class="' + cls + '">' + match + '</span>';
});
}
gethtmlcontents();
</script>
</head>
<body>
</body>
</html>
simplest way: save json file as *.js and include to html template as script.
js file like this:
let fileJsonData = {
someField: someValue,
...
}
include like this:
...
<script src="./js/jsonData.js"></script>
...
After include you can call to fileJsonData in global scope.
If you have Python installed on your local machine (or you don't mind install one), here is a browser-independent workaround for local JSON file access problem that I use:
Transform the JSON file into a JavaScript by creating a function that returns the data as JavaScript object. Then you can load it with <script> tag and call the function to get the data you want.
Here comes the Python code
import json
def json2js(jsonfilepath, functionname='getData'):
"""function converting json file to javascript file: json_data -> json_data.js
:param jsonfilepath: path to json file
:param functionname: name of javascript function which will return the data
:return None
"""
# load json data
with open(jsonfilepath,'r') as jsonfile:
data = json.load(jsonfile)
# write transformed javascript file
with open(jsonfilepath+'.js', 'w') as jsfile:
jsfile.write('function '+functionname+'(){return ')
jsfile.write(json.dumps(data))
jsfile.write(';}')
if __name__ == '__main__':
from sys import argv
l = len(argv)
if l == 2:
json2js(argv[1])
elif l == 3:
json2js(argv[1], argv[2])
else:
raise ValueError('Usage: python pathTo/json2js.py jsonfilepath [jsfunctionname]')

Categories

Resources