GenerateJSON

From Xojo Documentation

Method

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.).

Usage

result = GenerateJSON(value, expanded)

Part Type Description
result String JSON text.
value Variant The original value to be converted into JSON text.
expanded Boolean If True, the JSON returned includes white space that makes it more human-readable.

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.

Exceptions

Sample Code

Convert a simple array of Text to JSON data:

Var values() As String = Array("Red Sox", "Yankees", "Orioles", "Blue Jays", "Rays")
Var json As String = GenerateJSON(values)
// ["Red Sox","Yankees","Orioles","Blue Jays","Rays"]

Convert a Dictionary of values to JSON data:

Var d As New Dictionary
d.Value("Team") = "Red Sox"
d.Value("City") = "Boston"

Var json As String
json = GenerateJSON(d, True) // With expanded format
// {
// "Team": "Red Sox",
// "City": "Boston"
// }

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

Var dictArray() As Dictionary
Var d As Dictionary

d = New Dictionary
d.Value("Team") = "Red Sox"
d.Value("City") = "Boston"
dictArray.AddRow(d)

d = New Dictionary
d.Value("Team") = "Yankees"
d.Value("City") = "New York"
dictArray.AddRow(d)

Var json As String
json = GenerateJSON(dictArray)
// [{"City":"Boston","Team":"Red Sox"},{"City":"New York","Team":"Yankees"}]

See Also

ParseJSON method; JSONItem class