cancel
Showing results for 
Search instead for 
Did you mean: 

Problem with instantiating JSON object in script

Former Member
0 Kudos

Hi All,

I am having difficulty in DS 1.5 (P0 and P1) using JSON as a datatype for a variable in script.

The Application Designer Guide lists JSON in the Expression type system section, and also provides a reference to it in the example under the JSON listing in the API Reference. The example provided in the document is as follows:

var result = "";

var sample = {"key1": 100, "key2": 200};

  1. sample.forEach(function(value, key) {

result = result + "Key: " + key + " Value: " + value;

});

Whenever I try to use it in script I get a red cross which tells me "You cannot instantiate a JSON object". This prevents me from operating on the object in subsequent code.

Can anyone help me with where I am going wrong?

Thanks, Pat

Accepted Solutions (1)

Accepted Solutions (1)

Former Member
0 Kudos

Hi Patrick,

Can you please try in the below format to instantiate the JSON and to use in the substantiate scripts?

Ex.

var employees = [

    {"firstName":"John", "lastName":"Doe"},

    {"firstName":"Anna", "lastName":"Smith"},

    {"firstName":"Peter","lastName": "Jones"}

];

employees.forEach(function(element, index) {

  var x=employees[index]["firstName"] + " " + employees[index]["lastName"];

  APPLICATION.alert(x);

});


Hope this will help you.

Thanks,

Babu

Karol-K
Advisor
Advisor
0 Kudos

I just wanted to write "this will not work.." - but it works. I cannot believe it 😉

tested in 1.5 SP1

nice code, Babu!

reiner_hille-doering
Active Contributor
0 Kudos

Hi Ganesh,

Ouch - that this doesn't show tons of error message is in fact a bug. Also in this example BIAL doesn't have any type information about the JSONs.

I will probably fix it - what in this case means that you sample code would not work anymore.

Thanks,

Reiner.

Former Member
0 Kudos

Hi Babu,

That is great! It is exactly the kind of functionality I was hoping would be available in BIAL.

In fact, your code opens up another very interesting thing - the ability to retrieve an element from an array by specifying its index, rather than looping through it (which the doco in 32.3.1 says is the only way to do it). For example...

var myArray = ["Hello", "World"];

APPLICATION.alert(myArray[1]);

...works just fine! No loop required here.

Reiner - this sort of thing would be incredibly useful. It reduces code, makes scripts more readable (and might be better for performance).

Is it possible for this to become "supported", or at least a "feature" and not a bug?

Regards, Pat

Answers (4)

Answers (4)

reiner_hille-doering
Active Contributor
0 Kudos

Hello Patrick,

the sample if from the documentation of JSON forEach - and unfortunately the sample is wrong.

The idea how to loop over a JSON is correct, but you can't create JSON literals in Design Studio outside of a function argument.

What works:

var sel = CROSSTAB_1.getSelection();

sel.forEach(function(value, key) {

  APPLICATION.alert(key);

  value.forEach(function(element, index) {

      APPLICATION.alert(element);

});

});

In this case Design Studio knows that "sel" is a JSON where the keys are strings and the values arrays of string.

What also works:

var data = DS_1.getData("measure", { "Dim1:": "member1"});

In this case Design Studio known that the JSON literal must a JSON where key is a dimension key and value is a member key.

What can't work:

var j = { ... };

Why: Because Design Studio can't infer the type information of the JSON: What type is key and what type is value.

Do you think there is a need for having JSONs as variables  - which is not returned from another function?

Regards,

Reiner.

Former Member
0 Kudos

Hi Reiner,

Thank you very much for your reply - I will cancel my support ticket.

In answer to your question about having a need for JSONs as variables:

Admittedly I have been using Design Studio for some time now without it or feeling the need for it.

That said, I do think it would be incredibly useful if it were a supported feature. JSONs (and arrays of JSONs) are far more flexible than simple arrays for many tasks (particularly if certain JavaScript methods for accessing JSON properties are available to the designer). A couple of examples:

1) Array of JSON example - a simple lookup table:

var myPrice = 24.99;

var myJSONArray = [{"priceBarrier": 10.0, "category":"Low Cost Item", "color":"green"},

   {"priceBarrier": 20.0, "category":"Medium Cost Item", "color":"yellow"},

   {"priceBarrier": 30.0, "category":"High Cost Item", "color":"orange"},

   {"priceBarrier": 40.0, "category":"Very High Cost Item", "color":"red"}]

With the above structure you could take myPrice (say, 24.99), loop through the Array of JSONs to find the first entry (since an array is an ordered list) where myJSONArray[index]["priceBarrier"] <= myPrice.

This is a trivial example which could be handled by several arrays - but having several arrays means having several loops, whereas the above could be handled with a single loop (provided BIAL allows such looping and access to JSON values).

2) Customer detail object:

Imagine I have a application where I want to see the detail of that customer (name, address,  last 5 purchases, at risk of churn, etc.), along with trends/analytics for similar customers.

The detail of the customer is "for information" only - its only purpose is to provide context to the trends/analytics for similar customers. An example JSON for the customer details could be:

{

"customerId":1234,

"firstName":"Bob",

"lastName":"Example",

"address":{"line1":"1 Example Street",

    "City":"Exampleville",

    "PostCode":"212-ACDC",

    "Country":"Exampalia",

    "geoLat":"83.11232",

    "goeLong":"78.88979"

    }

"customerProfileKey":"asd-0012-elec-hv-8908",

"customerValue":"High",

"churnRisk":"Very High",

"lastFivePurchases":[{"purchaseId":12321, "purchaseDate":"2014-11-23", "purchaseItem":"Big Screen TV", "purchaseValue":1200.00},

  {"purchaseId":11210, "purchaseDate":"2014-06-12", "purchaseItem":"Power Board", "purchaseValue":35.99},

  {"purchaseId":12321, "purchaseDate":"2014-06-11", "purchaseItem":"Gaming Console", "purchaseValue":399.95}]

}

If Design Studio supported JSON variables/objects by provided methods to interact with them then I perhaps do the following:

a) In the warehouse, store the customer details JSON in a column in a customer dimension table (note that the JSON object is not massive, but is hierarchical and nested).

b) Retrieve this JSON via a DSL data source for several customers (Noting there may be a problem if the size of the JSON is above a certain limit - but I have had success returning UNX Long Text measures in a DS data source (admittedly there are tricks to it)).

c) For the first customer to be displayed, iterate through the customer detail JSON to populate a "Customer Information" area (since I know the JSON's schema, a full text view would work nicely here). I could also use the geoMaps component to show the customer's location.

d) Use some of the details returned in the customer detail ("customerProfileKey") to run other more "traditional" data source for trends/analytics.

I know this example is somewhat trivial as many of the customer details I have included in the JSON example could simply be returned as dimensions in a data source; however I'm hoping it gives an idea of the kind of thing I could see being achieved with it.

Sorry for the lengthy response!

Thanks Pat

Message was edited by: Patrick Godwin

reiner_hille-doering
Active Contributor
0 Kudos

Hi Patrick,

you examples look to me like data enrichment or mashup scenarios. This is an area where Xcelsius was strong and Design Studio is not so strong yet.

But scripting - especially with long constants - doesn't seem to be the best solution to me.

One - but complicated - solution for such mashups is implementing an SDK data source.

Maybe one day we come to a solution that is both - flexible and easy to use - and maintains some good MVC (model-view-controller) separation with ideally short scripts, HANA/BW data, enrichment data, and UI properties.

Reiner.

PS: It might be doable in BIAL to support JSON literals if I can detect the type of key and value - similar to Array literals where we detect the array type from the content. It might become impossible for some complex JSONs - and we can't always provide forEach on them - as this is not a standard JavaScript method.

Former Member
0 Kudos

Hi Reiner,

Thanks for the response.

I have come to a similar conclusion; design studio is not the tool for some of the applications I am designing. I am going to switch to more suitable approach (in my case this means ms + mvc) as it will be far more flexible and maintainable for what I need to do. A pity though, as BO provides a lot of nice built in features (security, semantic layer, lots of charting options, mobile support etc).

Cheers, Pat

reiner_hille-doering
Active Contributor
0 Kudos

Hi Pat,

fair statement. A good fit for your requirements might be SAPUI5 - providing MVC, data binding (through OData), mobile support (via sap.m lib) and almost the same Charting library that we use in Design Studio. And it targets JavaScript developers without any boundaries - while Design Studio targets IT professional that are usually no JavaScript developers.

Regards,

Reiner.

Former Member
0 Kudos

Hi Reiner,

The is probably not the correct forum, but I was wondering how I can find out about SAPUI5 licensing?

I've had a look at OpenUI5 and it looks great, but lacks certain things (like SAP.viz).

Our organisation holds BusinessObjects licences, but not any other SAP products (e.g. no HANA, no BW, no Netweaver etc.).

Is it likely that BO licence holders such as us are licenced for SAPUI5?

I understand that you might not be able to provide advice on licensing matters, and that I'll proabably have to take it up with our reseller, but if you could provide some direction/information I would really appreciate it.

Regards, Pat

Former Member
0 Kudos

Update: I've managed to get around the red cross error in a round-about fashion. See the code below:

var sample = [{"Key1" : "hello", "Key2" : "World"}];

sample.forEach(function(element, index) {

element.forEach(function(value, key) {  

  APPLICATION.alert(value);

});

});

Unfortunately when I try to run it gives me an "Error during script processing" message. Seems like there might be a problem with forEach on JSON after all. This is what appears in the error log:

Error during script processing: "ON_CLICK" "com.sap.ip.bi.zen.rt.framework.jsengine.JsEngineException: org.mozilla.javascript.EcmaError: TypeError: Cannot find function forEach in object [object Object]. (BIAL Script#5)

MustafaBensan
Active Contributor
0 Kudos

Yes, I had also tried this too with the same result .  As mentioned in my last response, the Design Studio SDK: JSON Object Component may meet your requirement until you hear back from SAP.

Former Member
0 Kudos

Thanks Mustafa,

Those community components are great!

In fact, using the JSONOBJECT utility is what got me on to this problem. At the moment the JSONOBJECT component does not have a method to retrieve a value by key. Naturally, I decided to use a method that returns a JSON object (getAsJSONObject), then loop over it with forEach. Unfortunately I ran into the above error.

I have a request in with the SCN community developers for the inclusion of a method to getValueByKey which should do the trick for me.

Thanks for your assistance.

Cheers, Pat

Karol-K
Advisor
Advisor
0 Kudos

Hi Patrick,

in standard this code can help you.

you can define an array, but you cannot put an object into the array - means you need 2 arrays.

var names = ["a", "b", "c"];

var values = [23, 34, 36];

names.forEach(function(elementName, indexName) {

  values.forEach(function(elementValue, indexValue) {

  if(indexName == indexValue) {

  APPLICATION.createInfoMessage("name: " + elementName + ", value: " + elementValue);

  }

  });

});

how do you want to use it actually?

Karol

Karol-K
Advisor
Advisor
0 Kudos

hi Pat, please log under https://github.com/org-scn-design-studio-community/sdkpackage/issues

we will try too look at this soon.

Karol

MustafaBensan
Active Contributor
0 Kudos

Hi Pat,

Yes, I think the community components are very helpful in complementing the standard.  I've also found the Collection Utility to be quite useful.

Regards,

Mustafa.

Former Member
0 Kudos

Hi Karol,

I have submitted an issue at above location. I have included quite a bit of detail as to how I imagine it would be used, including an example JSON on which I would like to operate.

Regards, Pat

Former Member
0 Kudos

Hi Karol,

I have submitted an issue to the SDK community github issues page. The example I have provided in the submission should give you a good idea of what I am looking to do.

Thanks, Pat

former_member110741
Product and Topic Expert
Product and Topic Expert
0 Kudos

Hi Patrick Godwin & Mustafa,

i  got error here as well var sample = {"key1": 100, "key2": 200};

Could you try the following code foreach for JSON using crosstab selection, this should work

var sel = CROSSTAB_1.getSelection(); 

var members = sel["0BC_VEND1__0BC_EVAL"]; //0BC_VEND1__0BC_EVAL dimension tech name

    members.forEach(function(element, index) {

     APPLICATION.alert(element);

    });

Regards,

Subhash

Former Member
0 Kudos

Hi Subhash,

Thanks for your response.

I am interested in using JSON objects in a generic fashion. For example, I might want to store data in a nested/hierarchical JSON object and manipulate it in script. The problem with this is that I cannot instantiate a JSON object as per the example provided in the Application Designer Guide.

Are you suggesting there is a way to achieve this through leveraging a crosstab component?

Regards, Pat

former_member110741
Product and Topic Expert
Product and Topic Expert
0 Kudos

Hi Patrick,

i see that instantiate is giving error - even for me too - this should get solve from SAP

you are correct, suggesting  that we can leverage JSON for components as well 🙂

Subhash

MustafaBensan
Active Contributor
0 Kudos

Hi Patrick,

This one has me stumped too.  I was able to replicate your JSON error as well.  It's either a documentation error or the functionality didn't make it into DS 1.5.  Perhaps a member of the Design Studio Team will chime in to confirm...

Regards,

Mustafa.

Former Member
0 Kudos

Thanks Mustafa, glad to know its not just me.

I've lodged a support case with SAP. I will post back here when I know more.

MustafaBensan
Active Contributor
0 Kudos

Hi Patrick,

In the interim, you may wish to consider using the Design Studio SDK: JSON Object Component from the SCN Design Studio SDK Development Community for instantiating and manipulating JSON objects.

Regards,

Mustafa.