How to display JSON data in a table using UI5

I am encountering an issue while trying to display JSON data in UI5. I have successfully loaded the data and can access it to show in individual fields, such as a text view. However, I am facing problems when attempting to display the data in a table.

Here is my current approach (implemented within the ajax success handler method):

var oModel1 = new sap.ui.model.json.JSONModel();  
var aData = jsonModel.getProperty("{/list}");
oModel1.setData({modelData : aData}); 
weatherTable.setModel(oModel1);  
weatherTable.bindRows("/modelData");  
weatherTable.placeAt('content'); 

The complete code snippet is updated within the script tag of index.html where the jsonModel is defined and not null.

<script>


            var url = "http://api.openweathermap.org/data/2.5/group?id=524901,703448,2643743&units=metric";

            jQuery.ajax({
                url : url,
                dataType : "json",
                success : function(data, textStatus, jqXHR){
                    var jsonModel = new sap.ui.model.json.JSONModel();
                    alert("status: " +textStatus);
                    alert(data);
                    jsonModel.setData(data);
                    sap.ui.getCore().setModel(jsonModel);


                    var weatherTable = new sap.ui.table.Table({
                        title : "Current Weather Details",
                        visibleRowCount : 4             
                    });

                    // Define columns for the table
                    ...

                    // Create a model and bind the table rows    
                    var oModel1 = new sap.ui.model.json.JSONModel();  
                    ...
                    weatherTable.setModel(oModel1);  
                    weatherTable.bindAggregation("rows","/modelData");  
                    weatherTable.placeAt('content'); 

                    // Additional UI elements
                    ...

                }
            });

</script>

When debugging, the issue seems to be with accessing the list through getProperty on the model which returns null.

Below is a sample of the JSON data returned:

{
  "cnt": 3,
  "list": [
    {
      ...
    },
    {
      ...
    },
    {
      ...
    }
  ]
}

Your suggestions are greatly appreciated. Looking forward to your responses.

Best regards, AW

Answer №1

Update answer after examining your code thoroughly:

  1. Make sure to remove the curly braces when calling the getProperty method of JSONModel.

    var aData = jsonModel.getProperty("/list")
    ;

  2. The binding path for your Table columns is incorrect. Include the sys path

           var weatherTable = new sap.ui.table.Table({
                    title : "Current Weather Details",
                    visibleRowCount : 4             
           });
    
    
    
           weatherTable.addColumn(new sap.ui.table.Column({
                    label : new sap.ui.commons.Label({text : "Name"}),               
                template : new sap.ui.commons.TextView().bindText("name")                
            }));
    
            weatherTable.addColumn(new sap.ui.table.Column({
                    label : new sap.ui.commons.Label({text : "Country"}),               
                template : new sap.ui.commons.TextView().bindText("sys/country")                
            }));
    
            weatherTable.addColumn(new sap.ui.table.Column({
                label : new sap.ui.commons.Label({text : "City"}),              
                template : new sap.ui.commons.TextView().bindText("sys/sunrise")
            }));
    
            weatherTable.addColumn(new sap.ui.table.Column({
                label : new sap.ui.commons.Label({text : "Weather"}),               
                template : new sap.ui.commons.TextView().bindText("sys/sunset")
            }));
    
            weatherTable.addColumn(new sap.ui.table.Column({
           label : new sap.ui.commons.Label({text : "Description"}),               
                  template : new sap.ui.commons.TextView().bindText("weather/0/description")
    }));
    

Answer №2

Your code indicates that the variable aData is becoming null. This could be due to the line of code where you have

var aData = jsonModel.getProperty("{/list}");
. The question arises, what exactly is the jsonModel referring to? Are you attempting to retrieve a model that was previously set somewhere in your code?

For instance:

sap.ui.getCore().setModel('jsonModel' , jsonData);  // Setting the model in core with name jsonModel

and then accessing this model using a variable like so.

var jsonModel = sap.ui.getCore().getModel('jsonModel');
var aData = jsonModel.getProperty('/list'); //please verify the path

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

What is the best method for encoding non-ASCII characters in JSON.stringify as ASCII-safe escaped characters (uXXXX) without the need for additional post-processing?

In order to send characters like ü to the server as unicode characters but in an ASCII-safe string format, I need them to be represented as \u00fc with 6 characters, rather than displaying the character itself. However, no matter what I try, after us ...

NPM: There are no valid TypeScript file rules specified

Currently working on a small project using React.JS. Whenever I execute : npm run start, the following message gets logged: Starting type checking and linting service... Using 1 worker with 2048MB memory limit Watching: /Users/John/Projects/myProject/src ...

retrieving JSON data within the controller

When I use the command console.log($scope.data), I am able to view my JSON file. Additionally, by using <div ng-repeat="item in data">, I can see all the items in the view. However, when I try console.log($scope.data[0]) or console.log($scope.data[0] ...

Removing the column name from a JSON return in C# involves using a variety of techniques

Below is a JSON output I have received : [ { positionCode: "POS1", positionName: "POSITION 1", positionDescription: "", parentPosition: "POS2", }, { positionCode: "POS2", positionName: "POSITION ...

Is there a way to filter out only the objects from the JSON data and exclude the strings?

I am facing an issue while looping through a JSON object. The presence of strings in the JSON is causing the loop to fail. How can I iterate only through the objects in the JSON without affecting the loop? My main goal is to iterate through the objects co ...

extract the key identifier from the JSON reply

My JSON ResponseData example for form0 is provided below: { "MaterialType": "camera", "AssetID": 202773, "forms": [ { "release": "asyncCmd/accessCameraMulti", "action": "rest/Asset/202773/cameraAccessMultiple", ...

Is there a way to properly structure the json data displayed in my network tab on Chrome?

After sending an http request to my backend, I received a json response in the network tab. However, the format of the json is unreadable. To clarify, here is a screenshot: https://i.stack.imgur.com/RBiTd.png Currently using Chrome, I am seeking assistanc ...

Fetching data using JSONRequest sample code

I am new to web development and this is my first attempt at using JSON. On the JSON website (http://www.json.org/JSONRequest.html), they recommend using JSONRequest.get for certain tasks. However, I keep running into an error stating "JSONRequest is not ...

Tips for Saving JSON Response from Fetch API into a JavaScript Object

I am facing an issue trying to store a Fetch API JSON as a JavaScript object in order to use it elsewhere. The console.log test is successful, however I am unable to access the data. The Following Works: It displays console entries with three to-do items: ...

Using ExtJS to populate a panel with data from various sources

I am currently working with an Ext.grid.GridPanel that is connected to a Ext.data.JsonStore for data and Ext.grid.ColumnModel for grid specifications. Out of the 10 columns in my grid, 9 are being populated by the json store without any issues. However, I ...

Issue encountered while loading JSON data into DynamoDB's local instance

I have successfully set up DynamoDB local and everything is functioning as expected after going through their documentation. I have also tested their example code, which worked flawlessly. The Users table has been created with the name "Users". Below is ...

Unable to Show the Contents of the Item - AngularJS

I'm in the process of developing an application that will showcase job details within a modal window based on the selected template. To achieve this, I've integrated ui.bootstrap and ui.router. However, I'm encountering difficulties in displ ...

Having trouble creating an angularjs table using ng-repeat in the controller?

I have a sample snippet that I would like to discuss. My goal is to display a JSON object in an angular table using ng-repeat, which is being generated from my angular controller script. I have attempted the code below, but for some reason, the table is no ...

What do you prefer: defining properties with the JSON object or with objectName.property in JavaScript

Can you tell me which approach is considered the best practice? Is it better to use the "this" statement in the following way: var obj = { x: 20, y: 10, width: this.x, height: this.y, render: function () { // renders object on canvas ctx.fi ...

Retrieve information in JSON format from a document

I'm trying to extract data from a JSON file without knowing the exact location of the data. Here is an example JSON: var names= [ { "category":"category1" , "name1":"david", "name2":"jhon", "name3":"peter" }, { "category":"catego ...

Having trouble retrieving all JSON properties

I am facing an issue with my json structure where I am unable to access certain properties. I can only access the main properties like type, properties, and so on within that hierarchy level. However, I cannot seem to access icon, iconURL, or title. The da ...

Error when parsing JSON due to the presence of backslashes within the serialized object

When trying to call a server side function and parse the response in client side using JavaScript and Ajax, I encountered a parse error. It seems that the issue lies with the backslash that the JavaScriptSerializer adds to serialize the object. The respons ...

What is the process for incorporating a unique Mongo expression into a JSON object?

I'm currently trying to figure out how to add a specific Mongo command to my JSON object. Normally, adding regular strings or objects is straightforward, but I'm struggling with this particular command: $set : { "author" : req.body.name } Simpl ...

Implementing Node.JS ajax to update current JSON information

I am seeking assistance in updating data within a JSON file using NODE.JS. Currently, my method adds the data with the same ID as expected. However, upon receiving the data back, it eliminates the last duplicate because it encounters the old value first. I ...

Traverse a collection of nested objects containing arrays as their values

Consider the following object: { "apples": [ "one", "two" ], "oranges": [ "three", "four" ] } If I want to find the value four within this object, how can I do so efficiently? Would a loop work, like the one shown below? for (var ...