whatsupmyname
whatsupmyname

Reputation: 31

How do fetch a JSON file when it does not have no parent?

Example of JSON file (Hello.json):

[
{
    "Name": "Alex Smith",
    "User": "1234",
    "Description": "Blue eyes"
},
{

This is what I have:

fetch('Hello.json')
.then(function (response) {
    return response.json();
})
.then(function (data) {
    var information = data.name[0];
    $('#information').append(information);

Can someone please explain what I am doing wrong or if there is a better way to do this? Thanks in advance

Upvotes: -1

Views: 118

Answers (2)

Strongsloth
Strongsloth

Reputation: 1

here's a revised code:

fetch('./Hello.json')
 .then( response => response.json())
 .then( data => {
   var information = data[0].Name;
   $('#information').append(information)
 })
.catch( error => {
throw new error(`Error: ${error}`)
})

What I modified:

  • Added a "./" before the Hello.json
  • Changed 'name' to 'Name' (due to the key name in json file)
  • Added Error handling in fetch()

Hope this helps :)

Upvotes: 0

Michał Moskal
Michał Moskal

Reputation: 328

Try:

var information = data[0].name;

You have an array of objects, so above should work.

Upvotes: 2

Related Questions