Is there a solution? [duplicate] - javascript

This question already has answers here:
How can I open a JSON file in JavaScript without jQuery?
(5 answers)
Closed 12 months ago.
So, i'm trying to run this code to put the information from the JSON file to the HTML page. This is the code im trying to run:
HTML:
<div id="gameContainer">
<script>
var games = "../games.json"
document.getElementById("gameContainer").innerHTML = `<h1>${games.author}</h1>`
</script>
</div>
games.json:
[
{
"name": "gameName",
"author": "authorName"
}
]
On the site, the html says "undefined" and that's it. No errors in the console, nothin.

You will have to fetch the file first in order to read the contents of the file.
const url = '../games.json';
const fetchJson = async () => {
try {
const data = await fetch(url);
const response = await data.json();
document.getElementById('gameContainer').innerHTML = `<h1>${response[0].author}</h1>`;
}
catch (error) {
console.log(error);
}
};
also, your games is an Array! So you need to use an Array index in order to then get the containing Object like: games[0].author, not games.author.

You cannot make a AJAX call to a local resource as the request is made using HTTP.
A workaround is to run a local webserver, serve up the file and make the AJAX call to localhost.
In terms of helping you write code to read JSON, you should read the documentation for jQuery.getJSON():
http://api.jquery.com/jQuery.getJSON
Here's a way to do it without jQuery.
First create this function:
function loadJSON(callback) {
var xobj = new XMLHttpRequest();
xobj.overrideMimeType("application/json");
xobj.open('GET', '../news_data.json', true);
xobj.onreadystatechange = function () {
if (xobj.readyState == 4 && xobj.status == "200") {
callback(JSON.parse(xobj.responseText));
}
};
xobj.send(null);
}
Then you can use it by simply calling something like this:
loadJSON(function(json) {
console.log(json); // this will log out the json object
});
source

Related

How to consume a local JSON file in my vanila JavaScript? [duplicate]

I have saved a JSON file in my local system and created a JavaScript file in order to read the JSON file and print data out. Here is the JSON file:
{"resource":"A","literals":["B","C","D"]}
Let’s say this is the path of the JSON file: /Users/Documents/workspace/test.json.
Could anyone please help me write a simple piece of code to read the JSON file and print the data in JavaScript?
For reading the external Local JSON file (data.json) using javascript, first create your data.json file:
data = '[{"name" : "Ashwin", "age" : "20"},{"name" : "Abhinandan", "age" : "20"}]';
Then,
Mention the path of the json file in the script source along with the javascript file
<script type="text/javascript" src="data.json"></script>
<script type="text/javascript" src="javascript.js"></script>
Get the Object from the json file
var mydata = JSON.parse(data);
alert(mydata[0].name);
alert(mydata[0].age);
alert(mydata[1].name);
alert(mydata[1].age);
For more information, see this reference.
The loading of a .json file from harddisk is an asynchronous operation and thus it needs to specify a callback function to execute after the file is loaded.
function readTextFile(file, callback) {
var rawFile = new XMLHttpRequest();
rawFile.overrideMimeType("application/json");
rawFile.open("GET", file, true);
rawFile.onreadystatechange = function() {
if (rawFile.readyState === 4 && rawFile.status == "200") {
callback(rawFile.responseText);
}
}
rawFile.send(null);
}
//usage:
readTextFile("/Users/Documents/workspace/test.json", function(text){
var data = JSON.parse(text);
console.log(data);
});
This function works also for loading a .html or .txt files, by overriding the mime type parameter to "text/html", "text/plain" etc.
You cannot make a AJAX call to a local resource as the request is made using HTTP.
A workaround is to run a local webserver, serve up the file and make the AJAX call to localhost.
In terms of helping you write code to read JSON, you should read the documentation for jQuery.getJSON():
http://api.jquery.com/jQuery.getJSON/
When in Node.js or when using require.js in the browser, you can simply do:
let json = require('/Users/Documents/workspace/test.json');
console.log(json, 'the json obj');
Do note: the file is loaded once, subsequent calls will use the cache.
Using the Fetch API is the easiest solution:
fetch("test.json")
.then(response => response.json())
.then(json => console.log(json));
It works perfect in Firefox, but in Chrome you have to customize security setting.
First, create a json file. In this example my file is words.json
[{"name":"ay","id":"533"},
{"name":"kiy","id":"33"},
{"name":"iy","id":"33"},
{"name":"iy","id":"3"},
{"name":"kiy","id":"35"},
{"name":"kiy","id":"34"}]
And here is my code i.e,node.js. Note the 'utf8' argument to readFileSync: this makes it return not a Buffer (although JSON.parse can handle it), but a string. I am creating a server to see the result...
var fs=require('fs');
var data=fs.readFileSync('words.json', 'utf8');
var words=JSON.parse(data);
var bodyparser=require('body-parser');
console.log(words);
var express=require('express');
var app=express();
var server=app.listen(3030,listening);
function listening(){
console.log("listening..");
}
app.use(express.static('website'));
app.use(bodyparser.urlencoded({extended:false}));
app.use(bodyparser.json());
When you want to read particular id details you can mention the code as..
app.get('/get/:id',function(req,res){
var i;
for(i=0;i<words.length;++i)
{
if(words[i].id==req.params.id){
res.send(words[i]);
}
}
console.log("success");
});
When you entered in url as localhost:3030/get/33 it will give the details related to that id....and you read by name also. My json file has simillar names with this code you can get one name details....and it didn't print all the simillar names
app.get('/get/:name',function(req,res){
var i;
for(i=0;i<words.length;++i)
{
if(words[i].id==req.params.name){
res.send(words[i]);
}
}
console.log("success");
});
And if you want to read simillar name details, you can use this code.
app.get('/get/name/:name',function(req,res){
word = words.filter(function(val){
return val.name === req.params.name;
});
res.send(word);
console.log("success");
});
If you want to read all the information in the file then use this code below.
app.get('/all',sendAll);
function sendAll(request,response){
response.send(words);
}
You can import It like ES6 module;
import data from "/Users/Documents/workspace/test.json"
As many people mentioned before, this doesn't work using an AJAX call. However, there's a way around it. Using the input element, you can select your file.
The file selected (.json) need to have this structure:
[
{"key": "value"},
{"key2": "value2"},
...
{"keyn": "valuen"},
]
<input type="file" id="get_the_file">
Then you can read the file using JS with FileReader():
document.getElementById("get_the_file").addEventListener("change", function() {
var file_to_read = document.getElementById("get_the_file").files[0];
var fileread = new FileReader();
fileread.onload = function(e) {
var content = e.target.result;
// console.log(content);
var intern = JSON.parse(content); // Array of Objects.
console.log(intern); // You can index every object
};
fileread.readAsText(file_to_read);
});
Very simple.
Rename your json file to ".js" instead ".json".
<script type="text/javascript" src="my_json.js"></script>
So follow your code normally.
<script type="text/javascript">
var obj = JSON.parse(contacts);
However, just for information, the content my json it's looks like the snip below.
contacts='[{"name":"bla bla", "email":bla bla, "address":"bla bla"}]';
Depending on your browser, you may access to your local files. But this may not work for all the users of your app.
To do this, you can try the instructions from here: http://www.html5rocks.com/en/tutorials/file/dndfiles/
Once your file is loaded, you can retrieve the data using:
var jsonData = JSON.parse(theTextContentOfMyFile);
If you are using local files, why not just packade the data as a js object?
data.js
MyData = { resource:"A",literals:["B","C","D"]}
No XMLHttpRequests, no parsing, just use MyData.resource directly
2021 solution (works in Chrome 91+)
The JS file where you're importing JSON file should be a module:
<script type="module" src="script.js"></script>
Then inside script.js import your json file:
import data from "./data.json" assert { type: "json" };
You can check that data is loaded with console.log(data)
Source
You can do this with fetch() with the help of async await. It is the latest and safest way of fetching data from url.
const url = "../asset/videoData.json";
const fetchJson = async () => {
try {
const data = await fetch(url);
const response = await data.json();
} catch (error) {
console.log(error);
}
};
You can use this for fetching data from external url also.
Just use $.getJSON and then $.each to iterate the pair Key /value.
Content example for the JSON file and functional code:
{
{
"key": "INFO",
"value": "This is an example."
}
}
var url = "file.json";
$.getJSON(url, function (data) {
$.each(data, function (key, model) {
if (model.key == "INFO") {
console.log(model.value)
}
})
});
All the solutions above mentioned will work only when you have a local webserver running on your local host. If you want to achieve this with out a web server, you might need to put in some manual effort by uploading the JSON file using file upload control. The browser will not offer this functionality with out a local server because of security risks.
You can parse the uploaded file with out a local webserver as well. Here is the sample code I have achieved a solution similar problem.
<div id="content">
<input type="file" name="inputfile" id="inputfile">
<br>
<h2>
<pre id="output"></pre>
</h2>
</div>
<script type="text/javascript">
document.getElementById('inputfile')
.addEventListener('change', function () {
let fileReader = new FileReader();
fileReader.onload = function () {
let parsedJSON = JSON.parse(fileReader.result);
console.log(parsedJSON);
// your code to consume the json
}
fileReader.readAsText(this.files[0]);
})
</script>
In my case I want to read a local JSON file and show it in a html file on my desktop, that's all I have to do.
Note: Don't try to automate the file uploading using JavaScript, even that's also not allowed due the same security restrictions imposed by browsers.
You can use XMLHttpRequest() method:
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var myObj = JSON.parse(this.responseText);
//console.log("Json parsed data is: " + JSON.stringify(myObj));
}
};
xmlhttp.open("GET", "your_file_name.json", true);
xmlhttp.send();
You can see the response of myObj using console.log statement(commented out).
If you know AngularJS, you can use $http:
MyController.$inject = ['myService'];
function MyController(myService){
var promise = myService.getJsonFileContents();
promise.then(function (response) {
var results = response.data;
console.log("The JSON response is: " + JSON.stringify(results));
})
.catch(function (error) {
console.log("Something went wrong.");
});
}
myService.$inject = ['$http'];
function myService($http){
var service = this;
service.getJsonFileContents = function () {
var response = $http({
method: "GET",
url: ("your_file_name.json")
});
return response;
};
}
If you have the file in a different folder, mention the complete path instead of filename.
Since you have a web application, you may have a client and a server.
If you have only your browser, and you want to read a local file from a javascript that is running in your browser, that means that you have only a client. For security reasons, the browser should not let you do such thing.
However, as lauhub explained above, this seems to work:
http://www.html5rocks.com/en/tutorials/file/dndfiles/
Other solution is to setup somewhere in your machine a web server (tiny in windows or monkey in linux) and with an XMLHttpRequest or D3 library, request the file from the server and read it. The server will fetch the file from the local filesystem, and serve it to you through the web.
If you could run a local web server (as Chris P suggested above), and if you could use jQuery, you could try http://api.jquery.com/jQuery.getJSON/
I liked what Stano/Meetar commented above. I use it to read .json files.
I have expanded their examples using Promise.
Here is the plunker for the same.
https://plnkr.co/edit/PaNhe1XizWZ7C0r3ZVQx?p=preview
function readTextFile(file, callback) {
var rawFile = new XMLHttpRequest();
rawFile.overrideMimeType("application/json");
rawFile.open("GET", file, true);
rawFile.onreadystatechange = function() {
if (rawFile.readyState === 4 && rawFile.status == "200") {
callback(rawFile.responseText);
}
}
rawFile.send(null);
}
//usage:
// readTextFile("DATA.json", function(text){
// var data = JSON.parse(text);
// console.log(data);
// });
var task1 = function (){
return new Promise (function(resolve, reject){
readTextFile("DATA.json", function(text){
var data = JSON.parse(text);
console.log('task1 called');
console.log(data);
resolve('task1 came back');
});
});
};
var task2 = function (){
return new Promise (function(resolve, reject){
readTextFile("DATA2.json", function(text){
var data2 = JSON.parse(text);
console.log('task2 called');
console.log(data2);
resolve('task2 came back');
});
});
}
Promise.race([task1(), task2()])
.then(function(fromResolve){
console.log(fromResolve);
});
The reading of JSON can be moved into another function, for DRY; but the example here is more of showcasing how to use promises.
You must create a new XMLHttpRequest instance and load the contents of the json file.
This tip work for me (https://codepen.io/KryptoniteDove/post/load-json-file-locally-using-pure-javascript):
function loadJSON(callback) {
var xobj = new XMLHttpRequest();
xobj.overrideMimeType("application/json");
xobj.open('GET', 'my_data.json', true); // Replace 'my_data' with the path to your file
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);
}
loadJSON(function(response) {
// Parse JSON string into object
var actual_JSON = JSON.parse(response);
});
You can use d3.js to import JSON files. Just call d3 on your html body:
<script src="https://d3js.org/d3.v5.min.js"></script>
Then put this on your js scripts:
d3.json("test.json").then(function(data_json) {
//do your stuff
})
Using jQuery and ajax works fine to read JSON file and manipulate the data
$(document).ready(function () {
$.ajax({
url: 'country.json',
type: 'GET',
dataType: 'json',
success: function (code, statut) {
for (let i in code) {
console.log(i)
}
}
});
});
Just wanted to provide another method since all above looked too complicated to me.
Works for me on my Chrome Version 95.0.4638.54.
Just quick and dirty js code
//read json document and remove the new line
var object = JSON.stringify(document.activeElement.textContent.replaceAll('\n',''));
//parse the string to json... don't know why but oje json.parse is not enough..
var json = JSON.parse(JSON.parse(object));
//read your json
json.items[0].contactInfo.firstName
//enjoy
Test json:
{
"items": [
{
"type": "test1",
"id": "test1",
"name": "test1",
"entityId": "test1",
"active": true,
"contactInfo": {
"company": "test1",
"firstName": "test1",
"email": "test1"
}
},
{
"type": "test2",
"id": "test2",
"name": "test2",
"entityId": "test2",
"active": true,
"contactInfo": {
"company": "test2",
"firstName": "test2",
"email": "test2"
}
}
]
}
You could use D3 to handle the callback, and load the local JSON file data.json, as follows:
<script src="//d3js.org/d3.v3.min.js" charset="utf-8"></script>
<script>
d3.json("data.json", function(error, data) {
if (error)
throw error;
console.log(data);
});
</script>
One simple workaround is to put your JSON file inside a locally running server. for that from the terminal go to your project folder and start the local server on some port number e.g 8181
python -m SimpleHTTPServer 8181
Then browsing to http://localhost:8181/ should display all of your files including the JSON. Remember to install python if you don't already have.
Turn the JSON file into a .js file and assign the json to a variable or const, then refer to it in your main javascript file.
I took Stano's excellent answer and wrapped it in a promise. This might be useful if you don't have an option like node or webpack to fall back on to load a json file from the file system:
// wrapped XMLHttpRequest in a promise
const readFileP = (file, options = {method:'get'}) =>
new Promise((resolve, reject) => {
let request = new XMLHttpRequest();
request.onload = resolve;
request.onerror = reject;
request.overrideMimeType("application/json");
request.open(options.method, file, true);
request.onreadystatechange = () => {
if (request.readyState === 4 && request.status === "200") {
resolve(request.responseText);
}
};
request.send(null);
});
You can call it like this:
readFileP('<path to file>')
.then(d => {
'<do something with the response data in d.srcElement.response>'
});
I have read the above and notice that usually in projects someone wants to have more than one json file to be loaded. In some cases a gazilion and in some cases "a directory of json files" (of which you would otherwise have to generate a list first to be able to download each of them). It get get messy if this is all over the project. And it can be a hassle if there are many relations between data in the json files.
Obviously that can all be done with the above methods, either making them .js files or retrieving them via some sort of local fetching.
However an alternative (if you do not want a server side solution with tiers) that I found useful is to first load all your data in a Sql Lite database. This makes managing more data also a bit easier and you only have one file with all your data etc...
Then you use web assembly to load your sqlite database and then you can use regular queries to query your data client-side. So this can all be done client-side
Here is an example: https://github.com/projectje/bookmarks-sync-sql-cogmios/blob/master/src/html/index.ts (typescript file that gets compiled to client-side solution).
In a read/write site you can deliver a sqlite database per user that you cache so that the data is unique for that user , etc.
ref: https://github.com/sql-js/sql.js

How to use JSON data to create an array

Okay so I want to be able to take a JSON file (external) and process it so that I can create an array that I can use to display the data.
JSON.parse() only works if I declare the JSON array then parse it, it does not work for external JSON data
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if(this.readyState == 4 && this.status == 200) {
console.log(JSON.parse(this.responseText.replace(/[u2018\u2019\u201c\u201D]/g,'"')));
document.getElementById("here").innerHTML =
console.log(myObj.Cardionotes[0].note);
}
}; xmlhttp.open("GET", "PATIENT51.txt", true);
xmlhttp.send();
};
I've used this question for help but I'm getting the same error- JSON.parse Error: Invalid character at position:3 (that's the middle of the if)
How do I turn a JSON file into an arraylist
Just use fetch() (or use a library like umbrella or jQuery) instead of trying to use AJAX without a library, you will want to bang your head into a wall once you discover all the problems there are with different implementations across browsers...:
const response = fetch('https://www.reddit.com/r/json.json')
.then((data) => {
// do your .replace(/[u2018\u2019\u201c\u201D]/g,'"') here, e.g.
// data.replace(/[u2018\u2019\u201c\u201D]/g,'"').json();
return data.json();
})
.then((json) => {
console.log(json);
})
.catch(err) => {
console.log(err);
});

jQuery to read file content to variable inside JavaScript [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 5 years ago.
I've searched for an answer for my particular predicament and I reckon it must have something to do with misunderstandings of my own (I'm new to JS). I know of similar topics but not quite addressing what I'd like to pin down - please forgive me if I have missed something previously posted.
I have boiled down what I'm trying to do to the following JavaScript which draws on jQuery's get to read file contents to a variable (I was trying to avoid all the hullabaloo involved in using XMLHttpRequest() just to read a file server-side):
window.onload = function(){
var refFile = "./myFile"; // path to my txt file
var fileContent;
$.get(refFile, function(response) {
fileContent = response;
alert(fileContent); // I get data here just fine
});
alert(fileContent); // undefined here - how can I have fileContent defined here?
}
If it's preferable to use XMLHttpRequest in pure JS instead that's fine, but I'd just like to know how to be able to make the value live outside the retrieving function - for use with other functions, for instance.
Any ideas on what I'm missing?
Any help would be much appreciated.
The $.get() function works asynchronous, so the fileContent doesn't contain the response because of this.
window.onload = function(){
var refFile = "./myFile"; // path to my txt file
var fileContent;
$.get(refFile, function(response) {
// do something here
}).done(function(response){
fileContent = response;
});
alert(fileContent); // not undefined anymore
}
Take a look at the documentation
This code should work for you.
var refFile = "./myfile"; // path to my txt file
function readBody(xhr) {
var data;
if (!xhr.responseType || xhr.responseType === "text") {
data = xhr.responseText;
} else if (xhr.responseType === "document") {
data = xhr.responseXML;
} else {
data = xhr.response;
}
return data;
}
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
console.log(readBody(xhr));
}
}
xhr.open('GET', refFile, true);
xhr.send(null);

How to save javascript variable or console.log(variable) to a file

I am using node and I have some code that I run that puts the data from an API call out in a certain JSON format I need for dynamo. It is about 23000 records or so a day and I am attempting to save them to my hard drive. Can someone please let me know how to save the output of a variable to a file? I have seen other pages on here but most of them seem to cover an html element with onclick or something along those lines. I appreciate any help.
In node to write in a new file or replace old
var fs = require('fs'); // reqire fileSystem node module
fs.writeFile("pathToFile", "Content", function(err) {
if(err) {
return console.log(err);
}
console.log("The file was saved!");
});
Or append to existing file
fs.appendFile("pathToFile", "Content", function (err) {
if (err) throw err;
console.log('Saved!');
});
One of the most common ways to log something from JavaScript is to use AJAX to post the value of the JavaScript variable. You can use any server-side script, including Node's FileSystem API to save a log of the variable to a specific file.
Example:
function saveVariable(variable) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
alert("Saved");
}
};
xhttp.open("POST", "save?var=" + variable, true);
xhttp.send();
}

How to load a text file in JavaScript?

I'm creating a simple WebGL project and need a way to load in models. I decided to use OBJ format so I need a way to load it in. The file is (going to be) stored on the server and my question is: how does one in JS load in a text file and scan it line by line, token by token (like with streams in C++)? I'm new to JS, hence my question. The easier way, the better.
UPDATE: I used your solution, broofa, but I'm not sure if I did it right. I load the data from a file in forEach loop you wrote but outside of it (i.e. after all your code) the object I've been filling data with is "undefined". What am I doing wrong? Here's the code:
var materialFilename;
function loadOBJModel(filename)
{
// ...
var req = new XMLHttpRequest();
req.open('GET', filename);
req.responseType = 'text';
req.onreadystatechange = function()
{
if (req.readyState == 4)
{
var lines = req.responseText.split(/\n/g);
lines.forEach(function(line)
{
readLine(line);
});
}
}
req.send();
alert(materialFilename);
// ...
}
function readLine(line)
{
// ...
else if (tokens[0] == "mtllib")
{
materialFilename = tokens[1];
}
// ...
}
You can use XMLHttpRequest to fetch the file, assuming it's coming from the same domain as your main web page. If not, and you have control over the server hosting your file, you can enable CORS without too much trouble. E.g.
To scan line-by-line, you can use split(). E.g. Something like this ...
var req = new XMLHttpRequest();
req.open('GET', '/your/url/goes/here');
req.onreadystatechange = function() {
if (req.readyState == 4) {
if (req.status == 200) {
var lines = req.responseText.split(/\n/g);
lines.forEach(function(line, i) {
// 'line' is a line of your file, 'i' is the line number (starting at 0)
});
} else {
// (something went wrong with the request)
}
}
}
req.send();
If you can't simply load the data with XHR or CORS, you could always use the JSON-P method by wrapping it with a JavaScript function and dynamically attaching the script tag to your page.
You would have a server-side script that would accept a callback parameter, and return something like callback1234(/* file data here */);.
Once you have the data, parsing should be trivial, but you will have to write your own parsing functions. Nothing exists for that out of the box.

Categories