learningUser
learningUser

Reputation: 482

How to parse a json object property to bind it to a control

I have following JSON data in a model named details. I want only the object which has key:"month" property in my table. For this there is a filter property in the control

   oData
   details:
   Array[4]
   0:Object
   1:Object
   2:Object
    editable:false
    key:"year"
    removeable:false
    value:"2000"
   3:Object
    editable:false
    key:"event"
    removeable:false
    value:"Day: TRUE, Night:False"
   4:Object
    editable:false
    key:"month"
    removeable:false
    value:"Time: August, Valid:True,from 2016"

The control is as follows

createContent : function(oController) {
 return new sap.m.Table({
   columns: [
               new sap.m.Column({
                header: new sap.m.Text({
                    text: 'value',
                })
            }),
   items: {
            path: '/details',
            filters: [ new sap.ui.model.Filter("key","EQ","month") ], //only display months
            template: new sap.m.ColumnListItem({
                cells: [
                        new sap.m.Text({
                        text: '{value}',
                    }),

Now in the UI I have only one column which displays

          Time: August, Valid:True,from 2016

I want to show the value in 2 columns. I am not able to make the items with text: '{value.time}'or text: '{value.valid}',

Upvotes: 0

Views: 429

Answers (1)

schnoedel
schnoedel

Reputation: 3948

The data "Time: August, Valid:True,from 2016" is a string. Its contents are not valid json.

But you can use a formatter to extract the needed part of the string:

createContent : function(oController) {
 return new sap.m.Table({
   columns: [
               new sap.m.Column({
                header: new sap.m.Text({
                    text: 'Time',
                })
            }),
               new sap.m.Column({
                header: new sap.m.Text({
                    text: 'Valid',
                })
            }),
   items: {
            path: '/details',
            filters: [ new sap.ui.model.Filter("key","EQ","month") ], //only display months
            template: new sap.m.ColumnListItem({
                cells: [
                        new sap.m.Text({
                        text: {path: "value", formatter: oController.extractTimeFromValue},
                    }),
                        new sap.m.Text({
                        text: {path: "value", formatter: oController.extractValidFromValue},
                    }),

Add the formatter functions in your controller like this:

extractTimeFromValue:function(value){
  var match = value.match(/Time:\s*(\w+)/);
  if (match){
    return match[1]; //return the first group (\w+)
  }
  return null;
},
extractValidFromValue:function(value){
  var match = value.match(/Valid:\s*(\w+)/);
  if (match){
    return match[1]; //return the first group (\w+)
  }
  return null; 
}

Upvotes: 1

Related Questions