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

The error message thrown is: "Unable to assign headers after they have already been sent to the client."

I've been attempting to make a GET request, but it keeps failing at the app.js res.json line. app.js app.use(function(err, req, res, next) { res.locals.message = err.message; res.locals.error = req.app.get("env") === "development" ? err : {}; ...

Ensure that the modal remains open in the event of a triggered keydown action, preventing it from automatically closing

I am currently toggling the visibility of some modals by adjusting their CSS properties. I would like them to remain displayed until there is no user interaction for a period of 3 seconds. Is there a way to achieve this using JavaScript? Preferably with Vu ...

Angular setPristine function is not functioning properly

I am looking to achieve a simple task - cleaning the $scope.user fields without encountering errors. if ($scope.contactForm.$valid) { $scope.user = {}; $scope.contactForm.$setPristine(); } However, I'm still experiencing v ...

Accessing JSON key by value alone

Imagine you have a variable storing the value of a key in a JSON object. Let's see... var stooges = [ {"id" : "a", "name" : "Moe"}, {"id" : "b", "name" : "Larry"}, {"id" : "c", "name" : "Shemp"} ]; var stooge = "Larry"; I am seeking gui ...

Is it possible for JavaScript to only work within the <script> tags and not in a separate .js

I'm facing a puzzling issue with my JavaScript code. It runs fine when placed directly within <script>...code...</script> tags, but refuses to work when linked from an external file like this: <SCRIPT SRC="http://website.com/download/o ...

Using Javascript to automatically replace content when the page is loaded

Having trouble with my fullCalendar jquery calendar and the 'eventClick' method. When I click on an event, the URL is getting encoded incorrectly. For example, I'm trying to pass a Wordpress URL like this: http://sitedomain.com/?post_type= ...

Unveiling the Power of AngularJS for Parsing JSON Data

A list of images is being generated in a table-like structure using the code snippet below. Each image represents a cell in this table, with its ID specifying its row and column position. <ul> <li class="row"> <ul> & ...

Click the button to save the text to your clipboard with a customized

Can anyone suggest a method for duplicating div text using JavaScript while preserving the style attributes (italics, font family, size, etc.)? My goal is to paste the copied text into Word and have it maintain the same appearance as on the webpage. For e ...

Displaying data in JSON format using CakePHP

I'm having difficulty formatting the content retrieved from my Controller as JSON in my view. Instead of displaying neatly like a typical JSON output, mine appears messy and unorganized. When I search for JSON online, I see outputs that look like thi ...

Tips for updating the left positioning of a Div element on the fly

Although my title may not fully explain my goal, I am dealing with dynamically created div elements. When a user triggers an ajax request to delete one of the divs, I want to remove it from the DOM upon success. The issue arises in adjusting the layout aft ...

What is the proper way to retrieve multiple property values stored in a property name using getJSON

I'm having trouble getting multiple languages to work in my code. Could someone assist me and provide guidance on how to write multiple choices for the property name language? When I input code like this to display only Dota 2 games in English, every ...

What could be causing Jest to prevent me from using the node testing environment, especially when they have made changes to it?

I am currently working on testing a React component within Next.js using Jest. Jest made an official announcement regarding the change of default test environment to Node: Due to this update, the default test environment has been switched from "jsd ...

The width of the Bootstrap row decreases with each subsequent row

I'm having trouble understanding this issue, as it seems like every time I try to align my rows in bootstrap, they keep getting smaller. Can anyone point out what mistake I might be making? ...

How can we stop a form from being submitted when the input field is

Similar Question: How to prevent submitting the HTML form’s input field value if it empty <?php include '../core/init.php'; if(isset($_POST['nt']) && isset($_POST['ntb'])){ mysql_query("INSERT INTO `pos ...

The JavaScript Autocomplete feature fails to clear suggestions when there is no user input detected

After watching a tutorial on using Javascript with Autocomplete and a JSON file, I implemented the code successfully. However, I encountered an issue: When I clear the input field, all results from the file are displayed. I've tried adding code to cl ...

What is the best way to set jade as a global variable in a node.js Express application?

Currently, the routing function shown below is operational: exports.summary = function(req, res, next) { var jade = require('jade'); res.render('myView', { main: jade.renderFile('./views/summary.jade') }); }; The ...

Determining the distance between two points in miles using Next.js

Are you familiar with the concept of geographical coordinates? Take for example these two points: point1 = {lat: 40.6974034, lng: -74.1197636} point2 = {lat: 42.694034, lng: -75.117636} My goal is to find the distance between these two poi ...

Cleaning up HTML strings in Angular may strip off attribute formatting

I've been experimenting and creating a function to dynamically generate form fields. Initially, the Angular sanitizer was removing <input> tags, so I discovered a way to work around this by bypassing the sanitation process for the HTML code stri ...

JavaScript encounters a parsing error when dealing with an async function

Ever since I developed a node.js web application, I've been utilizing MSSQL for the database. To streamline SQL functions, I crafted functions (sql.js) to handle all the necessary queries. Furthermore, I set up async function handlers (controllers.js) ...

The JQuery JavaScript function fails to complete its execution

Question: How can I resolve the issue where my PHP file returns a large JSON string with approximately 2000 elements, each having 14 child elements? When using jQuery AJAX to fetch the JSON and populate an ID-identified table, the filling process stops mid ...