Home > Net >  Unable to get length of JSON data in JS
Unable to get length of JSON data in JS

Time:01-12

I have a JSON file with some items. I'd like to randomly select one to display using Javascript. Here's the JSON file:

{
    "keywords": [
        {
            "name": "item1",
            "property1": "value1",
            "property2": "value2",
            "property3": "value3"
        },
        {
            "name": "item2",
            "property1": "value4",
            "property2": "value5",
            "property3": "value6"
        }
    ]
}

I fetch the file as follows:

let data;

function fetchJSON() {
    fetch('../keyworddata.json')
      .then(response => {
        if(!response.ok) throw new Error("HTTP status "   response.status);
        return response.json();
      })
      .then(jsonData => {
        data = jsonData;
      })
      .catch(error => {
        console.error('Error:', error);
      });
}

fetchJSON();

myData = JSON.parse(data);
lengthOfMyData = Object.keys(myData.keywords[0]).length;
console.log(lengthOfMyData);

However, I get the following error:

JSON Parse error: Unexpected identifier "object"

Can you help me? I'd like to find the number of items in the JSON file and then pick a random item from the list.

CodePudding user response:

There's some weirdness going on here: you're using a global variable for data associated with a function, your second then is wrong in terms of what you named things (response.json() parses JSON, it does not return JSON. It returns a normal JS datastructure, leading to the next bit) and you're trying to parse regular JS data as if it's JSON.

So let's fix all of that:

function fetchJSON(filename) {
  return fetch(filename)
    .then(response => response.json())
    .catch(error => {
      // Log error, and return an object that the consuming
      // code can still work with, but is effectively "empty"
      console.error({error});
      return { keywords: [] };
    });
}

const { keywords } = await fetchJSON(`../keywords.json`);
console.log(keywords.length);

Although it would make far more sense to not make fetchJSON handle the errors, and instead have the calling code have a try/catch so that if the fetch fails for whatever reason, your calling code knows where to branch next.

  • Related