Technology Blogs by Members
Explore a vibrant mix of technical expertise, industry insights, and tech buzz in member blogs covering SAP products, technology, and events. Get in the mix!
cancel
Showing results for 
Search instead for 
Did you mean: 
Hello Everyone,

The much-awaited JSON parse feature in SAP Cloud Application Studio (for SAP ByD and C4C) is here. Partners can now parse JSON using ABSL.

To parse JSON in ABSL, we faced a lot of difficulties and used string manipulation functions. But now we can use the new libraries to parse JSON format without any difficulties.

In version 2005 of the SAP Cloud Applications Studio, the following Reuse Library functions are new to JSON:


  1. Json.IsValidJson(json_string) : Returns true for valid JSON




  2. Json.GetArrayLength(keys, json_string): Returns the total array length for the keys passed.



  3. Json.ParseKeyValues(keys, json_string): Parses the JSON and provides value for the given keys.


To use this library and its functions, you must import the AP.PDI.Utilities namespace in ABSL script.

Sample JSON Format: 




1. Validation JSON format


This function allows you to check if the JSON string is valid or not. The output is a boolean value where True indicates valid JSON string and False indicates Invalid.

Syntax:
Json.IsValidJson(json_string)

 

Sample Code:
import ABSL;
import AP.PDI.Utilities;

var JsonString = "{\"d\": {\"results\": [{ \"__metadata\": { \"type\": \"EmployeeDetails.Employee\" }, \"UserID\": \"E12012\",\"RoleCode\": \"35\"}]}}";
var Result = Json.IsValidJson(JsonString);

 

2. Parse JSON KeyValues


This function allows us to get values for the desired key present in the JSON string. We can parse JSON using Json.ParseKeyValues() function.

The following parameters need to be filled:


  • KeysTable: Table consisting of keys for which value is required.




  • JsonStringJSON string consisting the keys passed




After executing the API, the function returns the following parameter in the resulting structure.


Result: A table consisting of the following columns:


  • Key: Key passed in the importing parameter.




  • Value: Value obtained for the key passed.




  • Error: Flag indicating an error; True if there is an error, else False.




  • Message: Information on why the error occurred (for example, Invalid key [Key_Name], if an invalid key is passed).




Syntax:
Json.ParseKeyValues(keys, json_string)

Sample Code:
import AP.PDI.Utilities;
import AP.Common.GDT;

var Result : JsonResult;
var keys : collectionof LANGUAGEINDEPENDENT_EXTENDED_Text;
var key ;

key = "d.results[1].UserID";//full path of key needs to be specified here
keys.Add(key);

key = "d.results[1].RoleCode";//full path of key needs to be specified here
keys.Add(key);

var JsonString = "{\"d\": {\"results\": [{ \"__metadata\": { \"type\": \"EmployeeDetails.Employee\" }, \"UserID\": \"E12012\",\"RoleCode\": \"35\"}]}}";
Result = Json.ParseKeyValues(keys, JsonString);

foreach(var res in Result.KeyValue)
{
var value = res.Value;
}



 

3. Get Array length of array present in JSON.


This function allows you to get the length of array present in JSON string. After executing the API, the function returns the following parameter in the resulting structure.

Result: A table consisting of the following columns:


  • Key: Key passed in the importing parameter.




  • Length: Numeric value representing array length; -1 is sent if any error occurs or passed key is not an array.




Syntax:
Json.GetArrayLength(keys, json_string)

Sample Code:
import AP.PDI.Utilities;
import AP.Common.GDT;

var Result : JsonArrayLength;
var keys : collectionof LANGUAGEINDEPENDENT_Text;
var key ;
key = "d.results";//valid key
keys.Add(key);

var JsonString = "{\"d\": {\"results\": [{ \"__metadata\": { \"type\": \"EmployeeDetails.Employee\" }, \"UserID\": \"E12012\",\"RoleCode\": \"35\"}]}}";
Result = Json.GetArrayLength (keys, JsonString);

foreach(var res in Result.Arraylength)
{
var value = res.Length;
}

 

Note: Full path of key needs to be specified.  don't use Key names to find the length. 

Advantages:-


  • JSON reuse library functions are very useful to parse JSON format.



  • No need for manual string manipulations to parse JSON anymore. Standard reuse functions can do that for us without any difficulties.


For example, you are using REST/OData web service and want to consume the JSON format using ABSL Script in SAP Cloud Application Studio. You can use the above-mentioned function to complete the development.

 

For more details please refer to SAP help documentation – JSON (Reuse Library) or   JSON Parse Help Document

 

I hope this new reuse function saves some effort for SDK developers out there.

 


Best Regards,

Anantharaj Sivalingam

22 Comments
Great post Anantharaj.

2nd and 3rd syntax got interchange I guess.. let me try out this.

Thanks

Anand
0 Kudos

Hi Anandakumar,

Apologies for the confusion. Now the Blog is updated!.

 

Thanks

Ananth

0 Kudos
Hi Ananth raj,

How can we pass the selection parameters in ABSL for odata. I mean use the replica of get method with filter criteria.

Any idea pls

Thanks.

Anand
ChrisWarken
Participant
0 Kudos
Hey Folks,

does anyone else have an issue when adding more than 50 keys to the table???

GetArrayLength() as well as ParseKeyValues() is returning an empty table then. I double checked my JSON string. Key strings are ok, JSON string is correct.

Regards

Christian

 
StefanM-AU
Employee
Employee
0 Kudos
Hi Christian,

Same issue for me.

I'm fetching an array of project records from external source via REST call, and want to parse three field values per array entry from the result.

With a page size of 10 (-> 30 key values) it is working fine. But with a page size of 20 (-> 60 key values) the result of Json.ParseKeyValues is empty.

I can parse the key values one by one per project record or in packages of 10, but this seems to be quite some runtime overhead.

Source Code:

...

var result = WebServiceUtilities.ExecuteRESTServiceWithoutEncoding(scenarioName, serviceName, httpMethod, httpResource, URLParameterList, headerParameterList, contentType, body);
var json = "{\"projects\": " + result.Content + "}";
var keys : collectionof LANGUAGEINDEPENDENT_EXTENDED_Text;
var key;

//Determine JSON Array Length
key = "projects";
keys.Add(key);
var L = Json.GetArrayLength(keys, json).Arraylength.GetFirst().Length;

var i = 1;
keys.Clear();
while (i <= L)
{
key = "projects[" + i.ToString() + "].PROJECTID";
keys.Add(key);
key = "projects[" + i.ToString() + "].VALUE";
keys.Add(key);
key = "projects[" + i.ToString() + "].TIME_STAMP";
keys.Add(key);
i = i + 1;
}
var jsonResult = Json.ParseKeyValues(keys,json);

...
ChrisWarken
Participant
0 Kudos

I opened an incident and SAP stated that the functions are in fact limited due to performance reasons.

My solution has several hundreds of records with 10 fields (at this very moment). I implemented a workaround that should also work for your example.

Just put another a keys.Clear() and also the ParseKeyValues function into your loop. You need to parse each record separately. Then you could write your jsonResult to a collection (or as I did to my custom “Record” BO and then to a Collection of Records)

As the records in my solution will have up to 150 fields, it will become very ugly to implement that. So I will open a case on influence.sap.com (and post the link here). Hopefully they will raise the limit ?

ChrisWarken
Participant
0 Kudos
I opened an improvement request on SAP portal. Please vote to get attention to that problem

https://influence.sap.com/sap/ino/#/idea/255288
former_member715559
Discoverer
0 Kudos

The Influence page - https://influence.sap.com/sap/ino/#/idea/255288 says that the Object does not exist and cannot upvote it.

Did you manage to solve the problem?

We have a similar issue, while adding values in loop and parsing in loop is a huge runtime overhead and just kills.

ChrisWarken
Participant
0 Kudos
Hi Pramodini,

You need to be logged in to the portal with your s-user. Then you should find it by searching for the request id 255288 or title "JSON Reuse Library - ridiculous limitation of key value number"

Hope that helped
former_member715559
Discoverer
0 Kudos
Hello Christian,

Actually not visible with my S-user and got it checked with one of my colleagues S-user as well with no luck.

Anyways We have a similar issue, while adding keys in loop and parsing in loop is a huge runtime overhead and just kills. Did you have a solution to it?

Our JSON has hundreds of items and just to Parse few items itself takes more than 30 mins. Where in our String parser is much very much quicker.

Any pointer would help, Thanks.

 

 
ChrisWarken
Participant
0 Kudos
I am searching like this:


 

And I am sorry. I dont have a universal solution to your problem.

 

Kind regards
sumit_mittal2
Active Contributor
0 Kudos
Hi Guys,

is there any restriction on the number of characters in json, which need to be parsed?

we are passing 1800 characters to parse the json and parsing is not returning any result.

we cant even copy paster the paylad its truncating after 1000 character.

please let me know if someone already aware about the json max. length which can be parsed?

thank you.

Sumit
Hi Guys,
Great blog, I'm stuck in fetching country in below JSON, can anyone help? Thanks in advance

{
"status":"OK",
"status-code":200,
"version":"1.0",
"total":36,
"access":"public",
"data":{
"AF":{
"country":"Afghanistan",
"region":"Asia"
}
,
"UZ":{
"country":"Uzbekistan",
"region":"Asia"
}
}
}
dhruv_mehta
Active Contributor
0 Kudos
Hi,

in general it should work, We are parsing below response :



    "response": {

        "node": "node1",

        "csrfToken": "a1oowzx4igtk1edxg0fk4fqkv",

        "startRow": 0,



{

                "version": 2,

                "typedId": "18551319.PX20",

                "name": "PURCHASE_COST",

                "sku": "MCXAG0200-1N2",

                "createDate": "2018-08-16T07:49:25",

                "createdBy": 8,

                "lastUpdateDate": "2019-03-27T11:02:07",

                "lastUpdateBy": 8,

                "attribute1": "SME",

                "attribute2": "L1",

                "attribute3": "P_BRW",

                "attribute4": "MCXAG0200-1N2",

                "attribute5": "EUR",

                "attribute6": "PC",

                "attribute7": xxx,

                "attribute8": 500,

                "attribute9": "2018-07-01",

                "attribute10": "2050-12-31",

                "attribute11": "JDE_PROD_MC",

                "attribute12": "MCXA",

                "attribute13": 200,

                "attribute14": "1N2",

                "attribute15": "SME_L1_P_BRW_PC_EUR_500_07/01/2018_JDE_PROD_MC",

                "attribute16": "no",

                "attribute17": "yes",

                "attribute18": null,

                "attribute19": null,

                "attribute20": null

            }

}


Above payload has only one record but we recieve 200+ records and parsing works.


May be if you can give example payload i can check from my system 🙂


BR

Dhruvin
motaz1991
Explorer
0 Kudos

Hello Guys,

I have the same issue with my developments, am receiving more than 200 records in the JSON string, but only the first 50 records are getting parsed with the ParseKeyValues function, and the rest is empty using key d.result[51,51,52, . ......]

 

Any Advise, workarounds.

Regards,

Moataz

 

 

 

 

motaz1991
Explorer
0 Kudos
Hello, Please clarify more how you achieve it.

 

BR
dhruv_mehta
Active Contributor
0 Kudos
can u post ur code in order to help u?
ashwin_narayan
Participant
0 Kudos
Hi ananth12,

 

Similar to this, i have a scenario where in i am getting the response in json array. And i have to use the length and then while loop to parse through each index to get the key.

Is there a better way than this to get the all the key values of complete array in one go ?

 

Thanks,

Ash
acc4cnps
Discoverer
What a low grade implementation of a json parser. It is absolutely useless in any real slightly more complex scenario.
0 Kudos
Hi Anantharaj,

 

Is there any re-use library function to convert below JSON date format to C4C date?

Or is there any way we can convert this JSON date to C4C date in ABSL?

/Date(253402214400000)/

 

Thanks.
0 Kudos
Hello Ankeet,

 

There are many ways to handle this type of Date format. I need more information.

 

Are you testing in the postman?. From where are you getting and posting the date format?

 

Can you give me more information about your requirement?

 

Thanks,

Anantharaj
óespinar
Participant
0 Kudos

Hi everyone,

Has anyone encountered time-out problems using this library?

I’m getting the standard "Error in AddOn Y..." email from SAP with dozens of time-outs on this line:

if( Json.IsValidJson( jsData ) == false )

In also on this one with no more than 10 keys:

jsonResult = Json.ParseKeyValues( jsonKeys, response.Body );

This is happening in different tenants and at different times, so I don’t think it’s a performance issue.

In my opinion, the behavior of this library is quite erratic.

Thanks,

Óscar

 

Labels in this area