A guide on parsing a nested JSON file with ExtJS 4

Here is the content of my JSON file named "jobInfo.json":

{
  "job": {
     "id": 1,
     "name": "Job 1",
     "description": "bla bla bla",
     "locations": {
        "type": "FeatureCollection",
        "features": [{
           "id": 1,
           "type": "Feature",
           "geometry": {
              "type": "Point",
              "coordinates": [9.523853, 47.671412]
           },
           "properties": {
              "name": "poi 1"
           }
        }, {
           "id": 2,
           "type": "Feature",
           "geometry": {
              "type": "Point",
              "coordinates": [9.484092, 47.650899]  
           },
           "properties": {
              "name": "poi 2"
           }
        }]
     }
  }
}

I am trying to read this file from ExtJS 4 in a unique way. In the initial step, I aim to extract the job properties 'name' and 'description'. A model has been attempted for this purpose:

Ext.define('VZ.model.Job', {
   extend: 'Ext.data.Model',
   alias: 'widget.jobmodel',
   idProperty: 'id',
   fields: [
      {
          name: 'id',
          type: 'integer'
      }, {
          name: 'name',
          type: 'string'
      }, {
          name: 'description',
          type: 'string'                            
      },
     'locations'
   ]
});

Below is how the controller should handle it:

var jobfile = "data/jobs/jobInfo.json"
var jobInfo = Ext.create('Ext.data.Store', {
        model: 'VZ.model.Job',
        proxy: {
           type: 'ajax',
           url: jobfile,
           reader: {
              type: 'json'
              root: 'job'
           }
        }
});

Unfortunately, this approach encountered an issue.

The next task involves accessing the property 'features' at the root level.

This was achieved with success using another JSON file ("data/jobs/job.json") that only contained features:

{
"type": "FeatureCollection",
"features": [{
    "id": 472
    "type": "Feature",
    "geometry": {
        "type": "Point",
        "coordinates": [9.523853, 47.671412]
    },
    "properties": {
        "name": "Flughafen"
    },
}, {
    "id": 458
    "type": "Feature",
    "geometry": {
        "type": "Point",
        "coordinates": [9.484092, 47.650899]
    },
    "properties": {
        "name": "Hafen"
    },

}]
}

By altering the code as shown below, the desired outcome can be achieved:

var jobfile = "data/jobs/job.json"
var jobStore = Ext.create('GeoExt.data.FeatureStore', {
    fields: [
        {name: 'name', type: 'string'}
    ],
    autoLoad: true,
    proxy: Ext.create('GeoExt.data.proxy.Protocol', {
        reader: Ext.create('GeoExt.data.reader.Feature', {**root: 'features'**}),
        protocol: new OpenLayers.Protocol.HTTP({
            url: jobfile
            format: new OpenLayers.Format.GeoJSON({
                internalProjection: new OpenLayers.Projection('EPSG:900913'),
                externalProjection: new OpenLayers.Projection('EPSG:4326')
            })
        })
    })
});

With this setup, the information can be utilized as a layer on openlayers.

However, when using "jobInfo.json", attempting to use 'job.locations.features' as the root led to the following error:

Uncaught TypeError: Cannot read property 'locations' of undefined

If anyone could assist me in resolving this issue, it would be greatly appreciated.

Thank you for your help in advance.

Answer №1

Your code has several issues that need to be addressed

- The URL should be passed to the proxy instead of the store
- Utilize associations when reading nested data

Below is a solution for your first issue in the code

Check out this working example:

Ext.define('VZ.model.Feature', {
   extend: 'Ext.data.Model',
   alias: 'widget.featuremodel',
   idProperty: 'id',
   fields: [
      {
          name: 'id',
          type: 'integer'
      }, {
          name: 'type',
          type: 'string'
      }, {
          name: 'geometry_type',
          type: 'string',
          mapping: 'geometry.type'
      }
   ]
});

Ext.define('VZ.model.Job', {
   extend: 'Ext.data.Model',
   alias: 'widget.jobmodel',
   idProperty: 'id',
   fields: [
      {
          name: 'id',
          type: 'integer'
      }, {
          name: 'name',
          type: 'string'
      }, {
          name: 'description',
          type: 'string'                            
      }
   ],
    associations: [{
        type: 'hasMany',
        model: 'VZ.model.Feature',
        name: 'features',
        associationKey: 'locations.features' // read child data from nested.child_groups
    }]
});


Ext.application({
    name : 'Fiddle',

    launch : function() {
        //Ext.Msg.alert('Fiddle', 'Welcome to Sencha Fiddle!');

        Ext.create('Ext.data.Store', {
            storeId: 'check',
            model: 'VZ.model.Job',
            proxy: {
                type: 'ajax',
                reader: {
                    type: 'json',
                    root: 'job'
                },
                url: 'jobinfo.json'
            },
            autoLoad: true
        });

        // allow time for data loading
        setTimeout(function() {
            var store = Ext.getStore('check');
            var rec = store.getAt(0);
            var astRec = rec.featuresStore.getAt(0);

            alert('Job Record ' + rec.get('description'));
            alert('Feature Record ' + astRec.get('geometry_type'));
        }, 1000);

    }
});

A JSON file modification is also required

{
  "job": [{
     "id": 1,
     "name": "Job 1",
     "description": "bla bla bla",
     "locations": {
        "type": "FeatureCollection",
        "features": [{
           "id": 1,
           "type": "Feature",
           "geometry": {
              "type": "Point",
              "coordinates": [9.523853, 47.671412]
           },
           "properties": {
              "name": "poi 1"
           }
        }, {
           "id": 2,
           "type": "Feature",
           "geometry": {
              "type": "Point",
              "coordinates": [9.484092, 47.650899]  
           },
           "properties": {
              "name": "poi 2"
           }
        }]
     }
  }]
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips on preventing duplication of APIs when retrieving data using nextjs

In my code, I have a function that can be called either from server-side rendering or client side: export const getData = async (): Promise<any> => { const response = await fetch(`/data`, { method: 'GET', headers: CONTENT_TYPE_ ...

Ajax request results in a 400 error code

Here is the structure of my Ajax call: function Submit() { var objectData = { email: $("#email").val(), firstName: $("#firstName").val(), lastName: $("#lastName").val(), loginMode: $("#login ...

"Steady layout of grid for the navigation bar and

Currently, I am in the process of developing a control panel with the use of HTML and CSS. To structure the page, I opted for a grid layout. However, I encountered an issue where the navbar and sidebar do not stay fixed on the screen despite trying various ...

Is there a way for me to calculate the square of a number generated by a function?

Just starting out with Javascript and coding, I'm having trouble squaring a number that comes from a function. I've outlined below what I am trying to achieve. Thank you in advance for your help. // CONVERT BINARY TO DECIMAL // (100110)2 > ( ...

Is it possible to deactivate an anchor tag based on the result of a conditional statement that returns a string?

I've created an anchor tag (not a button) with text that redirects me to another page <StyledTableCell align="center"> <Link href={`/races/results/${race.id}`}>{race.race_name}</Link> </StyledTableCell> There is a ...

Converting an object into Json format

I'm encountering an issue while trying to convert an object into Json format. The error message I am receiving from the code snippet below states "An instance of type string cannot be assigned to a variable of type JsonResult". Can someone please help ...

Information is cleared before it is transmitted

Let's begin with the following code: JavaScript: function keyPressed(e) // function for key press event { if (e.keyCode == 13) // 13 represents the enter key { $(this).val(""); } } $(document).ready(function () { $(' ...

Using jQuery UI autocomplete to insert the description of the selected item into a text field

Currently, I have a functional autocomplete text box with the following code: $('#material_number').autocomplete({ source: function(request, response) { $.ajax({ url: "index.cfm?action=leadtime.getmaterialleadtime& ...

How come the 'npm install canvas' command did not generate a JavaScript file as expected?

My venture into the world of node packages has just begun. I recently tried installing canvas to my project using this command: npm install canvas Prior to successfully executing the installation, it was necessary for me to first install gtk and cairo by ...

Dealing with errors when Ajax response is not defined

Trying to display errors when Ajax is unsuccessful, but struggling to access the specific error details. example Here is the information from the network tab playground {"message":"The given data was invalid.","errors":{"title":["The title field is requ ...

How to transform an image into a base64 string using Vue

I am having trouble converting a local image to base64. The function reader.readAsDataURL is not working for me. Instead of the image data, I always get 'undefined' assigned to the rawImg variable. The file variable contains metadata from the upl ...

In Python, what is the best way to update a text file and then reload it into JSON format?

I am trying to automatically reload my JSON data once the text file is updated by reopening it. Here is my code snippet: import json with open('np.txt') as np: np_data = np.read() np_list=json.loads(np_data) def reopen_file(): print(&qu ...

Securing chat messages with AES encryption using Websockets, Crypto.js, and .NET

Recently, I have implemented a user chat system using Websockets and ASP.MVC on the server. My goal was to ensure all messages sent and received through Websockets are encrypted (using AES). To achieve this, I decided to encrypt user messages before sendi ...

How can I iterate through JSON data and showcase it on an HTML page?

I am in the process of developing a weather application using The Weather API. So far, I have successfully retrieved the necessary data from the JSON and presented it in HTML format. My next goal is to extract hourly weather information from the JSON and ...

Implementing asynchronous file reading with module.exports in Node.js

Apologies in advance for what may seem like a basic question, but I'm delving into the inner workings of node and need help with a particular issue: I am trying to send an object or file from fs.readFile using require and module.exports. So far, this ...

javascript utilize jquery to advance saved event

When it comes to hyperlinks, I am pausing some of my native click events to verify if the resulting page contains the desired content. After storing the jquery event object and performing some validations, my goal is to allow the event to continue as usua ...

Performing an Ajax request to submit a form without the need to reload the page in MVC

I am looking for assistance with submitting a form from an MVC view without refreshing the page. However, it seems that my AJAX code below is not functioning properly: //here is ajax call function AjaxCallAndShowMessage(btnClick) { $('form').s ...

Steps for retrieving each element from a List of JSONObjects stored in ArrayList named 'json':

I am facing a challenge where I need to extract the value from an ArrayList<JSONObject>() similar to an ArrayList<List<String>>() For the ArrayList<List<String>>, I have implemented the following code for(List<String> ...

`switch tabs visibility based on checkbox selection`

There are 4 tabs available on a JSP page: Tab 1, Tab2, Tab3, and Tab4. Initially, only Tab1 is enabled, allowing users to freely work within that tab. However, Tabs 2, 3, and 4 are disabled, preventing users from accessing their contents. A checkbox is lo ...

What is the process for adding images from CSS (backgrounds, etc.) to the build folder with webpack?

Trying out the file loader for processing images and adding them to my build folder. Images within HTML files successfully show up in the build, but the ones from styles do not. I've divided my webpack configuration into two separate files and use t ...