How to use JSON data to create an array - javascript

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);
});

Related

Is there a solution? [duplicate]

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

"Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse" even though parsed json files are identical

I am a beginner. I started learning async javascript. I have encountered this
error when I was trying to parse through data from 3 different JSON files.
The files are nearely identitical. I even exchanged their data and still luigi file cannot be parsed. however other files get parsed even though the data in them was exchanged.
//javascript File
const getTodos = (resource,callback) => {
const request = new XMLHttpRequest();
request.addEventListener('readystatechange',()=>{
console.log(1);
if(request.readyState === 4 && request.status ===200)
{
const data = JSON.parse(request.responseText)
console.log(request,data);
callback(undefined,'could not fetch data');
}
else if(request.readystate === 4)
{
callback('could not fetch data',undefined);
}
});
request.open('GET',resource);
request.send();
};
getTodos('todos/luigi.json', (err,data) => {
console.log(data);
getTodos('todos/mario.json', (err,data) => {
console.log(data);
getTodos('todos/browser.json',(err,data) => {
console.log(data);
});
});
});
Mario JSON file
[{"text":"Make fun of browser","author":"Mario"},
{"text":"Make a painting","author":"Monalisa"},
{"text":"teach DBMS","author":"Manisha"}]
Luigi JSON file
[{"text":"Be a side kick","author":"Developers"},
{"text":"Green Mustache","author":"designers"},
{"text":"lead second","author":"devlopers"}]
Browser JSON file
[{"text":"Beat Up Mario","author":"Red"},
{"text":"Kidnapp Princess","author":"Yellow"},
{"text":"Debut in next game","author":"Pink"}]
ALl Json files are getting parsed except for luigi.json file
that error is only present when I try to parse luigi.json file

XMLHttpRequest - Which format does request.send(data) expect for data?

I have to use a XMLHttpRequest, but I don't know which data format is expected by the function request.send(). I searched for too long now.
I tried to pass a JSON object but it does not work:
var request = new XMLHttpRequest();
request.open("GET","fileApi");
var data = {
action: "read",
targetFile: "testFile"
};
request.addEventListener('load', function() {
if (request.status >= 200 && request.status < 300) {
$("#messageOutput").html(request.responseText);
} else {
console.warn(request.statusText, request.responseText);
}
});
request.send(data);
I get updateFile:155 XHR finished loading: GET "http://localhost/cut/public/fileApi".
But no data is received on the server. I made this simple check to approve this:
PHP (server side):
$action = filter_input(INPUT_GET, "action");
$targetFile = filter_input(INPUT_GET, "targetFile");
echo ("action = '$action' | targetFile = '$targetFile'");
exit();
Returns: action = '' | targetFile = ''
Unfortunatelly I can't use jQuery in my application, since the target is a C# Webbrowser (Internet Explorer) and it detects errors in the jQuery file and stops my scripts from working...
I don't know which data format is expected by the function request.send()
It can take a variety of formats. A string or a FormData object is most common. It will, in part, depend on what the server is expecting.
I tried to pass a JSON object
That's a JavaScript object, not a JSON object.
request.open("GET","fileApi");
You are making a GET request. GET requests should not have a request body, so you shouldn't pass any data to send() at all.
GET requests expect data to be encoded in the query string of the URL.
var data = {
action: "read",
targetFile: "testFile"
};
var searchParams = new URLSearchParams();
Object.keys(data).forEach((key) => searchParams.set(key, data[key]));
var url = "fileApi?" + searchParams;
console.log(url);
// and then…
// request.open("GET", url);
// request.send();
Warning: URLSearchParams is new and has limited browser support. Finding a library to generate a query string is left as a (simple) exercise to any reader who wants compatibility with older browsers.

Sending data from javascript to php file

I have this function that gets text from a php file on the server and plonks it into an HTML page.
What changes do I need to make to it to SEND data (just a couple of javascript variables) to the php file rather than read from it ? Hoping not many !!
function process() {
if (xmlHttp) // the object is not void
{
try {
xmlHttp.open("GET", "testAJAX.php", true);
xmlHttp.onreadystatechange = handleServerResponse;
xmlHttp.send(null);
} catch (e) {
alert(e.toString());
}
}
}
Take a look at what all headers you can make use of. In your case, you would want to use POST instead of GET
xmlHttp.open("POST", "testAJAX.php", true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");//or JSON if needed
xmlHttp.onreadystatechange = handleServerResponse;
xmlHttp.send(data);
You are probably better of using POST to send data it has less limitations. e.g:
var data = {
user: 'Joe',
age: 12
};
var httpReq = new XMLHttpRequest();
// true means async - you want this.
httpReq.open('POST', 'testAJAX.php', true);
// json is just a nice way of passing data between server and client
xmlhttpReq.setRequestHeader('Content-type', 'application/json');
// When the http state changes check if it was successful (http 200 OK and
// readyState is 4 which means complete and console out the php script response.
httpReq.onreadystatechange = function () {
if (httpReq.readyState != 4 || httpReq.status != 200) return;
console.log(httpReq.responseText);
};
httpReq.send(JSON.stringify(data));
And read it:
$name = json_decode($_POST['name']);
$age = json_decode($_POST['age']);
If it's just a couple of variables, you can pop them into the query string - although you'll want to make sure their values won't break your PHP script or open a security hole (for example, don't interpret user input as a SQL string). For more complicated data structures, use POST as others have suggested.
function process(var1value, var2value) {
if(xmlHttp) {
try {
xmlHttp.open("GET", "testAJAX.php?var1="+var1value+"&var2="+var2value, true);
xmlHttp.onreadystatechange = handleServerResponse;
xmlHttp.send(null);
} catch(e) {
alert(e.toString());
}
}
}

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