Method
ParseJSON
ParseJSON
Description
Parses JSON text and returns it as a Variant, which will typically contain a Dictionary or an array of Variant. Any returned Dictionary is case-sensitive.
Usage
result = ParseJSON(value)
Part |
Type |
Description |
---|---|---|
result |
Can contain a Dictionary or an Array. |
|
value |
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 |
A Variant containing Nil. |
A JSONException will be raised if the supplied JSON String is not valid JSON data.
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 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")
Compatibility
All project types on all supported operating systems.
See also
GenerateJSON function; JSONItem, Dictionary classes