Handling complex JSON data in KendoUI Grid with varying keys

I have come across a challenging issue with a complex SLC loopback query and the JSON format it returns. Despite my best efforts to find a solution, I seem to be struggling to grasp some of the answers or perhaps I am approaching the problem from the wrong angle.

The JSON format returned by the API looks like this:

> [ {"id":"1","name":"John", "type":"commercial", 
> "address":{"street1":"1 dalhousie lane", "street2":"some street"}},

> {"id":"2","name":"Jane", "type":"commercial", 
> "address":{"street1":"15 dalhousie lane", "postcode":"1283833"}},

> {"id":"3","name":"Jack", "address":{"street1":"12 dalhousie lane",
> "postcode":"9383833", "geo":{"lat":"9393939","long":"99393939"}}} 

Upon closer inspection, I have identified a couple of issues: 1. The JSON is nested with multiple levels. 2. There are inconsistencies and missing key values, such as missing "type" for "id":"2" and missing "geo" under "address" for "id":"3".

My attempt to display this JSON using the KendoUI grid resulted in errors like 'property undefined'. I understand the options available to me and what needs to be done:

  1. Define the schema: How can I handle missing keys?
  2. Parse the data?

I would greatly appreciate it if someone could guide me on how to proceed. Below is the code snippet for the grid:

$("#grid").kendoGrid({
    dataSource: {
        transport: {
            read: {
                url: apiurl,
                dataType: "json",
            }
        }
    },
    columns: [
        {
            field: "id",
            title: "User Id"
        },
        {
            field: "name",
            title: "User Name",
        },
        {
            field: "type",
            title: "User Type",
        },
        {
            field: "address.street1",
            title: "Street 1",
        },
        {
            field: "address.street2",
            title: "Street 2",
        },
        {
            field: "address.postcode",
            title: "Street 2",
        },
        {
            field: "address.geo.lat",
            title: "Latitude",
        },
        {
            field: "address.geo.long",
            title: "Longitude",
        }
    ]
});

Answer №1

If you want to customize your grid columns, you can utilize column templates:

columns: [
        {
            field: "id",
            title: "User ID"
        },
        {
            field: "name",
            title: "User Name",
        },
        {
            field: "type",
            title: "User Type",
            template: function(data) {
                         return data.type ? kendo.htmlEncode(data.type) : "";
                      }
        },
        {
            field: "address",
            title: "Street Address 1",
            template: function(data) {
                         return data.address.street1 ? kendo.htmlEncode(data.address.street1) : "";
                      }
        },
        {
            field: "address",
            title: "Street Address 2",
            template: function(data) {
                         return data.address.street2 ? kendo.htmlEncode(data.address.street2) : "";
                      }
        },
        {
            field: "address",
            title: "Postal Code",
            template: function(data) {
                         return data.address.postcode ? kendo.htmlEncode(data.address.postcode) : "";
                      }
        },
        {
            field: "address",
            title: "Latitude",
            template: function(data) {
                         return data.address.geo && data.address.geo.lat ? kendo.htmlEncode(data.address.geo.lat) : "";
                      }
        },
        {
            field: "address",
            title: "Longitude",
            template: function(data) {
                         return data.address.geo && data.address.geo.long ? kendo.htmlEncode(data.address.geo.long) : "";
                      }
        }
    ]

Each template function checks if the field exists and then displays the field value or an empty string.

Take a look at the live DEMO

Answer №2

To handle adding a default value for a missing field, you can utilize the schema.parse method. For more information, you can refer to the documentation provided at this link - http://docs.telerik.com/kendo-ui/api/javascript/data/datasource#configuration-schema.parse

<script>
var dataSource = new kendo.data.DataSource({
  transport: {
    read: {
      url: "yoururl",
      dataType: "jsonp"
    }
  },
  schema: {
    parse: function(response) {
      var items = [];
      for (var i = 0; i < response.length; i++) {
        var item = response[i];
        if(!item.address.geo){
             if(!item.address.geo.lat){
                  item.address.geo.lat = 0.0;
             }
        }
        
        items.push(item);
      }
      return items;
    }
  }
});
dataSource.fetch(function(){
  var data = dataSource.data();
  var product = data[0];
  console.log(product.name);
});
</script>

I hope this explanation proves useful.

Best, Wade

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

Error in Charts API - [draw function failed to render for one or more participants]

Currently encountering an error on the client side where one or more participants failed to draw. I am able to successfully output data in the drawVisualization call, indicating that the issue lies within the JavaScript code. Despite following examples, I ...

Update the input field's placeholder with the current date

Is it possible to dynamically set the placeholders for <input type='date' placeholder='{{ 'currentDate' }}'>? I have tried using the following variable: currentDate = this.datePipe.transform(new Date(), "yyyy-MM-dd& ...

NextJS getStaticProps failing to pass fetched data to the page component

Struggling with passing props from getStaticProps function into template pages in NextJS. Below is the code for the dynamic page template that I am using. // src/pages/blog/[slug].js import React from 'react'; import matter from 'gray-matte ...

The window.open() function is malfunctioning on Google Chrome

Within my vue.js application, I have encountered an issue when attempting to utilize window.open() to open a new tab. Strangely, whenever I use this method, the new tab opens briefly before immediately closing without loading any content. Surprisingly, win ...

Learn the process of implementing an SVG icon in your Angular Material project

I'm currently attempting to incorporate a single icon into my Angular Material application. Following the documentation, I have implemented $mdIconProvider in the following manner: app.config(function($stateProvider, $urlRouterProvider, $mdIconProvid ...

In Certain Circumstances, Redirects Are Applicable

I have set up Private Routing in my project. With this configuration, if there is a token stored in the localStorage, users can access private routes. If not, they will be redirected to the /404 page: const token = localStorage.getItem('token'); ...

What is the process for capturing a window screenshot using Node.js?

I am currently conducting research to discover a way to capture a screenshot of a window using Node.js. I have been attempting to achieve this with node-ffi, but I am facing some difficulties at the moment: var ffi = require('ffi'); var user32 ...

Error in Discord JS: Unable to access undefined properties (roles)

Currently, I am in the process of developing an event that will periodically check a MongoDB database for any expired keys and then proceed to remove a specific role from the corresponding member. const mongoose = require("mongoose") const { Disc ...

The switchView feature is currently malfunctioning and unable to access the content on the next page

For my application's admin panel design, I've divided my home into containers. The aim is to display details of clicked items in Images.html and Categories.html when a menu item in the 2nd container (also known as side bar) is clicked. However, m ...

Extract the text content from an HTML file while ignoring the tags to get the substring

Hello, I am a newcomer to the world of Web Development. I have an HTML document that serves as my resume, formatted in HTML. For example: html <p>Mobile: 12345678891 E-mail: <a href="<a href="/cdn-cgi/l/email-protection" class="__cf_email__" ...

Adjusting or cropping strokes in a JavaScript canvas

I am working with a transparent canvas size 200x200. The object is being drawn line by line on this canvas using the solid stroke method (lineTo()). I'm in need of making this object full-width either before or after ctx.stroke();. https://i.sstatic. ...

Creating a global variable in Angular that can be accessed by multiple components is a useful technique

Is there a way to create a global boolean variable that can be used across multiple components without using a service? I also need to ensure that any changes made to the variable in one component are reflected in all other components. How can this be ac ...

Identifying the JS Tree nodes that have been repositioned via drag-and-drop

I'm working with a JS Tree structure that includes drag and drop functionality. Here's the basic code I have so far: $('#using_html_1').jstree({ "core": { "check_callback":true }, "plugins" : ["dn ...

``After initialization, the service is unable to retrieve the object as

I have a special service that stores specific objects to be shared among different controllers. Here is an example of the code I am using: $rootScope.$on('controller.event', function(event, arg){ self.backendConnectorService.getBac ...

Enable users to provide ratings ranging from 0.5 up to 5

I recently created a rating component that allows users to rate on a scale from 0 to 4.5, with increments of 0.5, which is causing unexpected behavior. I actually want users to be able to rate from 0.5 to 5 instead. How can I achieve this adjustment? Below ...

Utilizing Angular 1.5 and ES6 to Enhance Dependency Injection

Hi there, I am currently exploring Angular and attempting to integrate ES6 into my workflow. I seem to be facing an issue with dependency injection where I cannot seem to get it working as expected. Here is a snippet from my index.js file: import ...

Swift--Importing JSON data

Currently utilizing Xcode 6.4 for programming in Swift. I am working on a program that needs to read JSON data from a URL. The sample JSON can be accessed at the following URL () and I have been using this online tool to parse the JSON for better readabil ...

Making a jQuery post request that returns JSON data

Is it possible to use the jQuery $.ajax method for making a POST request and sending data (e.g. page.aspx?var1=value) while also specifying that the expected response from the service will be in JSON format? var data = {name: _name, ...}; var request = $ ...

Exploring the Power of NPM Modules in an Electron Renderer

Having trouble accessing lodash in an electron renderer. I'm a beginner with Electron and know that both the main process and renderer (local html file) have access to node. I can require something from node core like fs and it works fine, but when I ...

Unexpected behavior with AJAX success function not being executed in jQuery despite console logs showing otherwise

I'm facing an issue with the following code snippet: $('a.like').on('click', function(e){ e.preventDefault(); var object_id = $(this).data('id'); var token = $(this).data('token'); ...