From Xojo Documentation

Revision as of 18:05, 22 January 2022 by Gperlman (talk | contribs) (Sample Code)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
You are currently browsing the old Xojo documentation site. Please visit the new Xojo documentation site!

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


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.


The Dictionary must consist of valid JSON. Here are some rules to follow:

  • Keys must be strings.
  • Values must be a valid JSON data type (String, Integer, Double, Dictionary Object, Array, Boolean or Nil). Currency is not a valid type that can be converted to JSON.
  • No generic Xojo objects.

Learn more about JSON syntax.

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.


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"

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

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

See Also

ParseJSON method; JSONItem class