Skip to content
Advertisement

How to pass data from a JSON file to a JavaScript class

I have a local JSON file with the following structure:

{ "project_id": 324,
  "project_name": "Project",
  "contributors": [
       { "name": "James", "dpto": "dpto1" },
       { "name": "Carl", "dpto": "dpto2" }] }

and a class project, which I’m not sure should be like this:

class project {
     constructor(id, name, contributors){
        this.id = id;
        this.name = name;
        this.contributors = contributors; 

Now, I can work with the data after using fetch, but I do not know how to use it outside of the response.

I want to fetch the JSON file and put it into a class I can use outside the response. Something like:

.fetch('project.json')
   .then(function (response) {
       return response.json();
   })
   .then(function (data) {
      // Class Project = data;
   })
   .catch(function (err) {
      console.log('error: ' + err);
});

//The data now can be used directly through the class.
Project.CallFunction();

I need to make quite a few manipulations with this data, and I’m not well versed in JavaScript, so I wanted to bring it to a more familiar territory and having something more tangible would make it easier to use.

Advertisement

Answer

You could have either a constructor that takes the JSON or a static method that returns an instance of the class from the data.

Taking your example, that would mean:

const project = await fetch('project.json')
   .then(function (response) {
       return response.json();
   })
   .then(function (data) {
      return new Project(data);
   })
   .catch(function (err) {
      console.log('error: ' + err);
   });

project would then be an instance of the Project class and contain the data.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement