0

In Ballerina I have a JSON object like this

json players = {
  "123": {"x":500, "y":400},
  "345": {"x": 300, "y":200}
}

I would like get an string from this object like:

string text = check <string>players;

This gives a runtime error:

'json' cannot be cast to 'string'

I am trying to get string representation of the JSON object and that is the reason I tried to cast it as above. What is the most suitable method to get a string representation of a JSON object in Ballerina?

Riyafa Abdul Hameed
  • 7,417
  • 6
  • 40
  • 55

2 Answers2

4

This can be done as follows:

string text = players.toString();

I wasn't aware that this function existed.

Riyafa Abdul Hameed
  • 7,417
  • 6
  • 40
  • 55
4

Adding more to Riyafa's answer, string str = check <string> someJson; will get the string value from a string-typed json. It will fail (with a runtime error) if the actual value of the json is something other than string (eg: number, boolean, json-array, json-object, etc).

So to get the string representation, despite the content of the json, someJson.toString() method should be used.

Supun Setunga
  • 314
  • 1
  • 4