Home > Software design >  How to traverse JSON object using a key like method name { "GROUP(date)": "2019-09&qu
How to traverse JSON object using a key like method name { "GROUP(date)": "2019-09&qu

Time:10-05

I have a json object like following

"values": {
      "GROUP(date)": "2019-09",
      "GROUP(account)": [
            {
                 "value": "228",
                 "text": "Subscription"
             }
         ],
       "SUM(amount)": "630.638",
}

The json object consists of key value pairs like above snippet. But the key is like method name coz there is a bracket like GROUP(date).

when I try to traverse using the key it not recognize the key. values.GROUP(date)

what is the way to get the value using this kind of key in ballerina?

CodePudding user response:

To use field access like values.GROUP(date), the parentheses can be escaped.

values.GROUP\(date\)

Alternatively, if the static type of values is a map (e.g., map<json> which represents JSON objects), member access can be used with a string literal.

values["GROUP(date)"]

CodePudding user response:

This is the answer that I found.


"values": {
      "GROUP(date)": "2019-09",
      "GROUP(account)": [
            {
                 "value": "228",
                 "text": "Subscription"
             }
         ],
       "SUM(amount)": "630.638",
}
         // direct call by key
         string date = values["GROUP(date)"].toString();
        
         // access value inside the array
         json[] account = <json[]> values["GROUP(account)"];
         map<json> account_obj = <map<json>> account[0];
         string account_value = check account_obj.text;

I tries to define a record and access the object. But wasn't able to have the approach.

  • Related