im trying to retrieve data from a json file using javascript.It works fine when I’m using it on certain parts of the api. An example of it working is here.
https://jsfiddle.net/4sv6nLuh/
I think it’s to do with the js file not properly reading the json file.
As shown in the link above, the json link works fine.
https://api.owler.cloud/v1/statuses/user_timeline/redux.json (this is a direct link) , because it is numbered from 0 to 3 in a count in loop.
But when i swap the data from something that doesn’t have each post counted in a iterated json list, like the json file below.
https://api.owler.cloud/v1/users/redux.json
I also don’t really want to use a library unless necessary, but i will if needed.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>JSON Test</title>
</head>
<body>
<div id="myData"></div>
<script>
fetch('https://api.owler.cloud/v1/users/bob.json')
.then(function (response) {
return response.json();
})
.then(function (data) {
appendData(data);
})
.catch(function (err) {
console.log('error: ' + err);
});
function appendData(data) {
var mainContainer = document.getElementById("myData");
for (var i = 0; i < data.length; i++) {
var div = document.createElement("div");
div.innerHTML = 'Name: ' + data[i].id + ' ' + data[i].name + data[i].screen_name + ' ' + data[i].location + data[i].description + ' ' + data[i].url + data[i].followers_count + ' ' + data[i].following_count + data[i].updates_count
;
mainContainer.appendChild(div);
}
}
</script>
</body>
</html>
I expected to output the relevant data fields from the json file using javascript, however im terrible at javascript and i’m not sure ho to removethe iteration loop for the fields to make it work.
3
Answers
When you don’t have an array of JSON objects, don’t use for loop to iterate. I see it’s just JSON object so you can directly get items. Here is the code:
data.length is null when the response just contains one json object. So all you need to do is check if data.length is not null before iterating through the json list. If it is null then just create the div element for the one json object. This way it can work for both responses with a json list or one json object.
It seems like you are hitting wrong endpoint of api.
Docs go through the docs and see what you can and cannot do with the api.