Save JSONObject - javascript

what kind of object is this?
I am trying to craft mock data in order to test an application and this is how one of my fake data looks like. How can I save this mock data?
I could only thought of using the JSON.stringify function and copy the result to save as a string. Obviously, after I do that, I would have no access to the attribute of the original object.
Are there any ways I can write this JSONObject into a file and have access to its properties later??

JSON.stringify() returns a string. To make an object you can access properties of again, you'll need to pass that string through JSON.parse().
It's also worth noting that if the object you're saving has any functions in it, they will not be saved.

In your code obj is a javascript object
You can use blob (https://developer.mozilla.org/en-US/docs/Web/API/Blob) and HTML5 download API to do the required as:
var json = JSON.stringify(obj);
var blob = new Blob([json], {type: "application/json"});
var url = URL.createObjectURL(blob);
var a = document.createElement('a');
a.download = "mydata.json";
a.href = url;
a.textContent = "Download mydata.json";
You can load that data and access it properties later using and XMLHttpRequest GET request as:
function loadJSON(callback) {
var getobj = new XMLHttpRequest();
getobj.overrideMimeType("application/json");
getobj.open('GET', 'mydata.json', true); // Replace 'mydata' with the path to your file
getobj.onreadystatechange = function () {
if (getobj.readyState == 4 && getobj.status == "200") {
// Required use of an anonymous callback as .open will NOT return a value but simply returns undefined in asynchronous mode
callback(getobj.responseText);
}
};
getobj.send(null);
}
loadJSON(function(response) {
// Parse JSON string into object
var savedData = JSON.parse(response);
});

Using local storage maybe.
localStorage.setItem("MYMockData", JSON.stringify(fakeData));
var fakeDataRetrived = JSON.parse(localStorage.getItem("MYMockData"));

Related

Load multiple JSON files in pure JavaScript

I am new to JavaScript. I have already understood how to create an object from a JSON-file with JSON.Parse() and now I need to load multiple local JSONs into an array. I've been googling my problem for a while, but everything that I found was related to single JSON files.
Is there any way to do this in pure JavaScript without any libraries like jQuery and etc.?
P.S.: There is no need to work with web-server or else, the code is running locally.
To do this, you need to first get the actual files. Then, you should parse them.
// we need a function to load files
// done is a "callback" function
// so you call it once you're finished and pass whatever you want
// in this case, we're passing the `responseText` of the XML request
var loadFile = function (filePath, done) {
var xhr = new XMLHTTPRequest();
xhr.onload = function () { return done(this.responseText) }
xhr.open("GET", filePath, true);
xhr.send();
}
// paths to all of your files
var myFiles = [ "file1", "file2", "file3" ];
// where you want to store the data
var jsonData = [];
// loop through each file
myFiles.forEach(function (file, i) {
// and call loadFile
// note how a function is passed as the second parameter
// that's the callback function
loadFile(file, function (responseText) {
// we set jsonData[i] to the parse data since the requests
// will not necessarily come in order
// so we can't use JSONdata.push(JSON.parse(responseText));
// if the order doesn't matter, you can use push
jsonData[i] = JSON.parse(responseText);
// or you could choose not to store it in an array.
// whatever you decide to do with it, it is available as
// responseText within this scope (unparsed!)
}
})
If you can't make an XML Request, you can also use a file reader object:
var loadLocalFile = function (filePath, done) {
var fr = new FileReader();
fr.onload = function () { return done(this.result); }
fr.readAsText(filePath);
}
You can do something like this:
var file1 = JSON.parse(file1);
var file2 = JSON.parse(file2);
var file3 = JSON.parse(file3);
var myFileArray = [file1, file2, file3];
// Do other stuff
// ....
// Add another file to the array
var file4 = JSON.parse(file4);
myFileArray.push(file4);
If you already have an array of un-parsed files you could do this:
var myFileArray = [];
for(var i=0; i<unparsedFileArray.length; i++){
myFileArray.push(JON.parse(unparsedFileArray[i]));
}

File API - Blob to JSON

I'm trying to do some experiment with HTML5, WebSocket and File API.
I'm using the Tomcat7 WebSocket implementation.
I'm able to send and received text messages from the servlet. What I want to do now is to send from the servlet to the client JSON objects, but I want to avoid text message in order to skip the JSON.parse (or similar) on the client, so I'm trying to send binary messages.
The servlet part is really simple:
String s = "{arr : [1,2]}";
CharBuffer cbuf = CharBuffer.wrap(s);
CharsetEncoder encoder = Charset.forName("UTF-8").newEncoder();
getWsOutbound().writeBinaryMessage(encoder.encode(cbuf));
getWsOutbound().flush();
After this message, on the client I see that I received a binary frame, that is converted to a Blob object (http://www.w3.org/TR/FileAPI/#dfn-Blob).
The question is: is it possible to get the JSON object from the Blob?
I took a look at the FileReader interface (http://www.w3.org/TR/FileAPI/#FileReader-interface), and I used code like this to inspect what the FileReader can do (the first line creates a brand new Blob, so you can test on the fly if you want):
var b = new Blob([{"test": "toast"}], {type : "application/json"});
var fr = new FileReader();
fr.onload = function(evt) {
var res = evt.target.result;
console.log("onload",arguments, res, typeof res);
};
fr.readAsArrayBuffer(b);
using all the "readAs..." methods that I saw on the File Reader implementation (I'm using Chrome 22). Anyway I didn't find something useful.
Did you have any suggestion? Thanks.
You should have tried readAsText() instead of readAsArrayBuffer() (JSON is text in the end).
You've also missed to stringify the object (convert to JSON text)
var b = new Blob([JSON.stringify({"test": "toast"})], {type : "application/json"}),
fr = new FileReader();
fr.onload = function() {
console.log(JSON.parse(this.result))
};
fr.readAsText(b);
To convert Blob/File that contains JSON data to a JavaScript object use it:
JSON.parse(await blob.text());
The example:
Select a JSON file, then you can use it in the browser's console (json object).
const input = document.createElement("input");
input.type = "file";
input.accept = "application/json";
document.body.prepend(input);
input.addEventListener("change", async event => {
const json = JSON.parse(await input.files[0].text());
console.log("json", json);
globalThis.json = json;
});
What you're doing is conceptually wrong. JSON is a string representation of an object, not an object itself. So, when you send a binary representation of JSON over the wire, you're sending a binary representation of the string. There's no way to get around parsing JSON on the client side to convert a JSON string to a JavaScript Object.
You absolutely should always send JSON as text to the client, and you should always call JSON.parse. Nothing else is going to be easy for you.
let reader = new FileReader()
reader.onload = e => {
if (e.target.readyState === 2) {
let res = {}
if (window.TextDecoder) {
const enc = new TextDecoder('utf-8')
res = JSON.parse(enc.decode(new Uint8Array(e.target.result))) //转化成json对象
} else {
res = JSON.parse(String.fromCharCode.apply(null, new Uint8Array(e.target.result)))
}
console.info('import-back:: ', res)
}
}
reader.readAsArrayBuffer(response)

How do I pass along variables with XMLHTTPRequest

How do I send variables to the server with XMLHTTPRequest? Would I just add them to the end of the URL of the GET request, like ?variable1=?variable2=, etc?
So more or less:
XMLHttpRequest("GET", "blahblah.psp?variable1=?" + var1 + "?variable2=" + var2, true)
If you want to pass variables to the server using GET that would be the way yes. Remember to escape (urlencode) them properly!
It is also possible to use POST, if you dont want your variables to be visible.
A complete sample would be:
var url = "bla.php";
var params = "somevariable=somevalue&anothervariable=anothervalue";
var http = new XMLHttpRequest();
http.open("GET", url+"?"+params, true);
http.onreadystatechange = function()
{
if(http.readyState == 4 && http.status == 200) {
alert(http.responseText);
}
}
http.send(null);
To test this, (using PHP) you could var_dump $_GET to see what you retrieve.
Manually formatting the query string is fine for simple situations. But it can become tedious when there are many parameters.
You could write a simple utility function that handles building the query formatting for you.
function formatParams( params ){
return "?" + Object
.keys(params)
.map(function(key){
return key+"="+encodeURIComponent(params[key])
})
.join("&")
}
And you would use it this way to build a request.
var endpoint = "https://api.example.com/endpoint"
var params = {
a: 1,
b: 2,
c: 3
}
var url = endpoint + formatParams(params)
//=> "https://api.example.com/endpoint?a=1&b=2&c=3"
There are many utility functions available for manipulating URL's. If you have JQuery in your project you could give http://api.jquery.com/jquery.param/ a try.
It is similar to the above example function, but handles recursively serializing nested objects and arrays.
If you're allergic to string concatenation and don't need IE compatibility, you can use URL and URLSearchParams:
const target = new URL('https://example.com/endpoint');
const params = new URLSearchParams();
params.set('var1', 'foo');
params.set('var2', 'bar');
target.search = params.toString();
console.log(target);
Or to convert an entire object's worth of parameters:
const paramsObject = {
var1: 'foo',
var2: 'bar'
};
const target = new URL('https://example.com/endpoint');
target.search = new URLSearchParams(paramsObject).toString();
console.log(target);
The correct format for passing variables in a GET request is
?variable1=value1&variable2=value2&variable3=value3...
^ ---notice &--- ^
But essentially, you have the right idea.
Following is correct way:
xmlhttp.open("GET","getuser.php?fname="+abc ,true);
Yes that's the correct method to do it with a GET request.
However, please remember that multiple query string parameters should be separated with &
eg. ?variable1=value1&variable2=value2
How about?
function callHttpService(url, params){
// Assume params contains key/value request params
let queryStrings = '';
for(let key in params){
queryStrings += `${key}=${params[key]}&`
}
const fullUrl = `${url}?queryStrings`
//make http request with fullUrl
}

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]')

Is it possible to save a File object in LocalStorage and then reload a File via FileReader when a user comes back to a page?

For example, say the user loads some very large images or media files in to your web app. When they return you want your app to show what they've previously loaded, but can't keep the actual file data in LocalStorage because the data is too large.
This is NOT possible with localStorage. Data stored in localStorage needs to be one of the primitive types that can be serializable. This does not include the File object.
For example, this will not work as you'd expect:
var el = document.createElement('input');
el.type='file';
el.onchange = function(e) {
localStorage.file = JSON.stringify(this.files[0]);
// LATER ON...
var reader = new FileReader();
reader.onload = function(e) {
var result = this.result; // never reaches here.
};
reader.readAsText(JSON.parse(localStorage.f));
};
document.body.appendChild(el);
The solution is to use a more powerful storage option like writing the file contents to the HTML5 Filesystem or stashing it in IndexedDB.
Technically you can if you just need to save small files in localStorage.
Just base64 that ish and since it's a string... it's localStorage-friendly.
I think localStorage has a ~5MB limit. base64 strings are pretty low file size so this is a feasible way to store small images. If you use this lazy man's way, the downside is you'll have to mind the 5MB limit. I think it could def be a solution depending on your needs.
Yes, this is possible. You can insert whatever information about the file you want into LocalStorage, provided you serialize it to one of the primitive types supported. You can also serialize the whole file into LocalStorage and retrieve that later if you want, but there are limitations on the size of the file depending on browser.
The following shows how to achieve this using two different approaches:
(function () {
// localStorage with image
var storageFiles = JSON.parse(localStorage.getItem("storageFiles")) || {},
elephant = document.getElementById("elephant"),
storageFilesDate = storageFiles.date,
date = new Date(),
todaysDate = (date.getMonth() + 1).toString() + date.getDate().toString();
// Compare date and create localStorage if it's not existing/too old
if (typeof storageFilesDate === "undefined" || storageFilesDate < todaysDate) {
// Take action when the image has loaded
elephant.addEventListener("load", function () {
var imgCanvas = document.createElement("canvas"),
imgContext = imgCanvas.getContext("2d");
// Make sure canvas is as big as the picture
imgCanvas.width = elephant.width;
imgCanvas.height = elephant.height;
// Draw image into canvas element
imgContext.drawImage(elephant, 0, 0, elephant.width, elephant.height);
// Save image as a data URL
storageFiles.elephant = imgCanvas.toDataURL("image/png");
// Set date for localStorage
storageFiles.date = todaysDate;
// Save as JSON in localStorage
try {
localStorage.setItem("storageFiles", JSON.stringify(storageFiles));
}
catch (e) {
console.log("Storage failed: " + e);
}
}, false);
// Set initial image src
elephant.setAttribute("src", "elephant.png");
}
else {
// Use image from localStorage
elephant.setAttribute("src", storageFiles.elephant);
}
// Getting a file through XMLHttpRequest as an arraybuffer and creating a Blob
var rhinoStorage = localStorage.getItem("rhino"),
rhino = document.getElementById("rhino");
if (rhinoStorage) {
// Reuse existing Data URL from localStorage
rhino.setAttribute("src", rhinoStorage);
}
else {
// Create XHR, BlobBuilder and FileReader objects
var xhr = new XMLHttpRequest(),
blob,
fileReader = new FileReader();
xhr.open("GET", "rhino.png", true);
// Set the responseType to arraybuffer. "blob" is an option too, rendering BlobBuilder unnecessary, but the support for "blob" is not widespread enough yet
xhr.responseType = "arraybuffer";
xhr.addEventListener("load", function () {
if (xhr.status === 200) {
// Create a blob from the response
blob = new Blob([xhr.response], {type: "image/png"});
// onload needed since Google Chrome doesn't support addEventListener for FileReader
fileReader.onload = function (evt) {
// Read out file contents as a Data URL
var result = evt.target.result;
// Set image src to Data URL
rhino.setAttribute("src", result);
// Store Data URL in localStorage
try {
localStorage.setItem("rhino", result);
}
catch (e) {
console.log("Storage failed: " + e);
}
};
// Load blob as Data URL
fileReader.readAsDataURL(blob);
}
}, false);
// Send XHR
xhr.send();
}
})();
Source

Categories

Resources