Xojo.Data.GenerateJSON

From Xojo Documentation

You are currently browsing the old Xojo documentation site. Please visit the new Xojo documentation site!
Method

Xojo.Data.GenerateJSON(value As Auto) As Text

Supported for all project types and targets.

Generates JSON text from the supplied value, which is typically a Dictionary, an array of Dictionaries or an array of primitive data types (Integer, Text, etc.).

Notes

The order of data in a Dictionary is not guaranteed to match the order in the generated JSON. Order is retained for arrays. You can actually supply a single value that is not a Dictionary or an array and get it back as a single valid JSON object (it will encode quotes in text, for example), but those are not valid JSON by themselves.

Currency is not a valid type that can be converted to JSON.

fa-exclamation-circle-32.png
An InvalidArgumentException will be raised if one of the types in value cannot be converted to a JSON data type.

Sample Code

Convert a simple array of Text to JSON data:

Dim values() As Text = Array("Red Sox", "Yankees", "Orioles", "Blue Jays", "Rays")
Dim json As Text = Xojo.Data.GenerateJSON(values)
// ["Red Sox","Yankees","Orioles","Blue Jays","Rays"]

Convert a Dictionary of values to JSON data:

Dim d As New Xojo.Core.Dictionary
d.Value("Team") = "Red Sox"
d.Value("City") = "Boston"

Dim json As Text
json = Xojo.Data.GenerateJSON(d)
// {"City":"Boston","Team":"Red Sox"}

If you want to store an array of information, create an array of Dictionaries and use that to generate the JSON:

Dim dictArray() As Xojo.Core.Dictionary
Dim d As Xojo.Core.Dictionary

d = New Xojo.Core.Dictionary
d.Value("Team") = "Red Sox"
d.Value("City") = "Boston"
dictArray.Append(d)

d = New Xojo.Core.Dictionary
d.Value("Team") = "Yankees"
d.Value("City") = "New York"
dictArray.Append(d)

Dim json As Text
json = Xojo.Data.GenerateJSON(dictArray)
// [{"City":"Boston","Team":"Red Sox"},{"City":"New York","Team":"Yankees"}]