ParseJSON

From Xojo Documentation

Method

Parses JSON text and returns it as a Variant, which will typically contain a 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.

Usage

result = ParseJSON(value)

Part Type Description
result Variant Can contain a Dictionary or an Array.
value String The original JSON as a String.

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 Variant containing a numeric type such as Integer or Double.
String Variant containing a String.
Boolean Variant containing a Boolean.
Array, noted by [] Variant containing array: Variant()
Value Variant containing the value.
Object, noted by {} Variant 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"]
Var names() As Variant
names = ParseJSON(json)

Var teamNames() As String
For Each name As String In names
teamNames.Add(name)
Next

Convert JSON data to a Dictionary:

// jsonText contains actual JSON data:
// {"City":"Boston","Team":"Red Sox"}
Var dict As Dictionary
dict = 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"}]
Var jsonArray() As Variant
jsonArray = ParseJSON(kJsonData)

Var nyTeam As String = Dictionary(jsonArray(1)).Value("Team")
// nyTeam = "Yankees"

// Now loop through the array
Var dict As Dictionary
Var value As String
For Each d As 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}}

Var d As Dictionary
d = ParseJSON(jsonData)
Var topPlayer As Dictionary = d.Value("topplayer")
Var playerName As String = topPlayer.Value("name")