Xojo.Data.ParseJSON

From Xojo Documentation

Method

Xojo.Data.ParseJSON(json As Text) As Auto

Supported for all project types and targets.

Parses JSON text and returns it as an Auto, which will typically contain a Xojo.Core.Dictionary, an array of Dictionaries or an array of primitive data types (Integer, Text, etc.) depending on the JSON text. If the returned value contains a Dictionary, it is case-sensitive.

Notes

The order of information in the JSON text is not guaranteed to match the order of the information in the resulting Dictionary. Order is retained for arrays. When looking at JSON, arrays are denoted by the use of square brackets ([]) to identify the array. Curly braces identify objects.

JSON data types map to corresponding Xojo types as follows:

JSON Data Type Xojo Data Type
Number Auto containing a numeric type such as Integer or Double.
String Auto containing a Text.
Boolean Auto containing a Boolean.
Array, noted by [] Auto containing array: Auto()
Value Auto containing the value.
Object, noted by {} Auto containing a Dictionary.
Whitespace n/a
Null Auto is Nil.

Exceptions

Sample Code

Convert JSON data (in array form) back to an array (note the user of the square bracket surrounding the JSON text elements):

// json contains actual JSON data:
// ["Red Sox","Yankees","Orioles","Blue Jays","Rays"]
Dim names() As Auto
names = Xojo.Data.ParseJSON(json)

Dim teamNames() As Text
For Each name As Text In names
teamNames.Append(name)
Next

Convert JSON data to a Dictionary:

// jsonText contains actual JSON data:
// {"City":"Boston","Team":"Red Sox"}
Dim dict As Xojo.Core.Dictionary
dict = Xojo.Data.ParseJSON(jsonText)

To load a JSON data array into an array of Dictionaries:

// kJsonData contains the actual JSON data in a Constant:
// [{"City":"Boston","Team":"Red Sox"},{"City":"New York","Team":"Yankees"}]
Dim jsonArray() As Auto
jsonArray = Xojo.Data.ParseJSON(kJsonData)

Dim nyTeam As Text = Xojo.Core.Dictionary(jsonArray(1)).Value("Team")
// nyTeam = "Yankees"

// Now loop through the array
Dim dict As Xojo.Core.Dictionary
Dim value As Text
For Each d As Xojo.Core.Dictionary In jsonArray
value = d.Value("Team")
Next

To get a value that is within an object in the JSON data, you assign the object to a Dictionary and then reference the value it contains:

// jsonData contains the actual JSON data:
// {"team":"Red Sox","topplayer":{"name":"David Ortiz", "position":"DH", "uniform number":34}}

Dim d As Xojo.Core.Dictionary
d = Xojo.Data.ParseJSON(jsonData)
Dim topPlayer As Xojo.Core.Dictionary = d.Value("topplayer")
Dim playerName As Text = topPlayer.Value("name")