PureBasic JSON: A Quick Tutorial

Share your advanced PureBasic knowledge/code with the community.
User avatar
TI-994A
Addict
Addict
Posts: 2490
Joined: Sat Feb 19, 2011 3:47 am
Location: Singapore

PureBasic JSON: A Quick Tutorial

Post by TI-994A »

A QUICK & SIMPLE TUTORIAL ON JSON FUNCTIONS

With the almost indispensable use of web services nowadays, the concepts and use of JSON are quite important. The best way to understand any concept is through experimentation. So here's a step-by-step guide to demonstrate the use of PureBasic's JSON functions.

PART 1: WRITING JSON DATA

Creating a JSON data placeholder

Code: Select all

#json = 0

; create an empty json placeholder
If CreateJSON(#json)
  
  Debug "an empty JSON placeholder:"
  Debug "> " + ComposeJSON(#json) + #CRLF$
  
  ; clear & release the json object
  FreeJSON(#json)
  
EndIf

Code: Select all

an empty JSON placeholder:
> null
Creating a JSON data object

Code: Select all

#json = 0

; create an empty json placeholder
If CreateJSON(#json)
  
  ; sets the created json placeholder as a json object
  jsonObject = SetJSONObject(JSONValue(#json))
  
  Debug "an empty JSON object:"
  Debug "> " + ComposeJSON(#json) + #CRLF$
  
  ; clear & release the json object
  FreeJSON(#json)
  
EndIf

Code: Select all

an empty JSON object:
> {}
Inserting a key-value pair into the JSON object

Code: Select all

#json = 0

; create an empty json placeholder
If CreateJSON(#json)
  
  ; sets the created json placeholder as a json object
  jsonObject = SetJSONObject(JSONValue(#json))
  
  ; insert a key-value pair into the json object
  jsonElement = AddJSONMember(jsonObject, "Key 1")
  SetJSONString(jsonElement, "Value 1")

  Debug "the JSON object with one key-value pair:"
  Debug "> " + ComposeJSON(#json) + #CRLF$
  
  ; clear & release the json object
  FreeJSON(#json)
  
EndIf

Code: Select all

the JSON object with one key-value pair:
> {"Key 1":"Value 1"}
Inserting another key-value pair into the JSON object

Code: Select all

#json = 0

; create an empty json placeholder
If CreateJSON(#json)
  
  ; sets the created json placeholder as a json object
  jsonObject = SetJSONObject(JSONValue(#json))
  
  ; insert a key-value pair into the json object
  jsonElement = AddJSONMember(jsonObject, "Key 1")
  SetJSONString(jsonElement, "Value 1")
  
  ; insert another key-value pair into the json object
  jsonElement = AddJSONMember(jsonObject, "Key 2")
  SetJSONString(jsonElement, "Value 2")
  
  Debug "the JSON object with two key-value pairs:"
  Debug "> " + ComposeJSON(#json) + #CRLF$
  
  ; clear & release the json object
  FreeJSON(#json)
  
EndIf

Code: Select all

the JSON object with two key-value pairs:
> {"Key 1":"Value 1","Key 2":"Value 2"}
Formatting the JSON output

Code: Select all

#json = 0

; create an empty json placeholder
If CreateJSON(#json)
  
  ; sets the created json placeholder as a json object
  jsonObject = SetJSONObject(JSONValue(#json))
  
  ; insert a key-value pair into the json object
  jsonElement = AddJSONMember(jsonObject, "Key 1")
  SetJSONString(jsonElement, "Value 1")
  
  ; insert another key-value pair into the json object
  jsonElement = AddJSONMember(jsonObject, "Key 2")
  SetJSONString(jsonElement, "Value 2")
  
  Debug "the JSON object with formatted output:"
  Debug ComposeJSON(#json, #PB_JSON_PrettyPrint) + #CRLF$
  
  ; clear & release the json object
  FreeJSON(#json)
  
EndIf

Code: Select all

the JSON object with formatted output:
{
  "Key 1": "Value 1",
  "Key 2": "Value 2"
}
Inserting another key-value pair with a numerical value

Code: Select all

#json = 0

; create an empty json placeholder
If CreateJSON(#json)
  
  ; sets the created json placeholder as a json object
  jsonObject = SetJSONObject(JSONValue(#json))
  
  ; insert a key-value pair into the json object
  jsonElement = AddJSONMember(jsonObject, "Key 1")
  SetJSONString(jsonElement, "Value 1")
  
  ; insert another key-value pair into the json object
  jsonElement = AddJSONMember(jsonObject, "Key 2")
  SetJSONString(jsonElement, "Value 2")
  
  ; insert another key-value pair with a numeric value
  jsonElement = AddJSONMember(jsonObject, "Key 3")
  SetJSONInteger(jsonElement, 3)
  
  Debug "a JSON object with numerical data (without quotes):"
  Debug ComposeJSON(#json, #PB_JSON_PrettyPrint) + #CRLF$
  
  ; clear & release the json object
  FreeJSON(#json)
  
EndIf

Code: Select all

a JSON object with numerical data (without quotes):
{
  "Key 1": "Value 1",
  "Key 2": "Value 2",
  "Key 3": 3
}
Inserting an array into the JSON object

Code: Select all

#json = 0

; create an empty json placeholder
If CreateJSON(#json)
  
  ; sets the created json placeholder as a json object
  jsonObject = SetJSONObject(JSONValue(#json))
  
  ; insert a key-value pair into the json object
  jsonElement = AddJSONMember(jsonObject, "Key 1")
  SetJSONString(jsonElement, "Value 1")
  
  ; insert another key-value pair into the json object
  jsonElement = AddJSONMember(jsonObject, "Key 2")
  SetJSONString(jsonElement, "Value 2")
  
  ; insert another key-value pair with a numeric value
  jsonElement = AddJSONMember(jsonObject, "Key 3")
  SetJSONInteger(jsonElement, 3)
  
  ; insert an array into the json object
  jsonArray = AddJSONMember(jsonObject, "Key 4")
  SetJSONArray(jsonArray)
  
  Debug "the JSON object with an empty array object:"
  Debug ComposeJSON(#json, #PB_JSON_PrettyPrint) + #CRLF$
  
  ; clear & release the json object
  FreeJSON(#json)
  
EndIf

Code: Select all

the JSON object with an empty array object:
{
  "Key 1": "Value 1",
  "Key 2": "Value 2",
  "Key 3": 3,
  "Key 4": []
}
Inserting a string value into the JSON object array

Code: Select all

#json = 0

; create an empty json placeholder
If CreateJSON(#json)
  
  ; sets the created json placeholder as a json object
  jsonObject = SetJSONObject(JSONValue(#json))
  
  ; insert a key-value pair into the json object
  jsonElement = AddJSONMember(jsonObject, "Key 1")
  SetJSONString(jsonElement, "Value 1")
  
  ; insert another key-value pair into the json object
  jsonElement = AddJSONMember(jsonObject, "Key 2")
  SetJSONString(jsonElement, "Value 2")
  
  ; insert another key-value pair with a numeric value
  jsonElement = AddJSONMember(jsonObject, "Key 3")
  SetJSONInteger(jsonElement, 3)
  
  ; insert an array into the json object
  jsonArray = AddJSONMember(jsonObject, "Key 4")
  SetJSONArray(jsonArray)
  
  ; insert a value into the array object
  jsonArrayElements = AddJSONElement(jsonArray)
  SetJSONString(jsonArrayElements, "String 1") 
  
  Debug "the JSON object with one array entry:"
  Debug ComposeJSON(#json, #PB_JSON_PrettyPrint) + #CRLF$
  
  ; clear & release the json object
  FreeJSON(#json)
  
EndIf

Code: Select all

the JSON object with one array entry:
{
  "Key 1": "Value 1",
  "Key 2": "Value 2",
  "Key 3": 3,
  "Key 4": [
      "String 1"
    ]
}
Inserting a double value into the JSON object array

Code: Select all

#json = 0

; create an empty json placeholder
If CreateJSON(#json)
  
  ; sets the created json placeholder as a json object
  jsonObject = SetJSONObject(JSONValue(#json))
  
  ; insert a key-value pair into the json object
  jsonElement = AddJSONMember(jsonObject, "Key 1")
  SetJSONString(jsonElement, "Value 1")
  
  ; insert another key-value pair into the json object
  jsonElement = AddJSONMember(jsonObject, "Key 2")
  SetJSONString(jsonElement, "Value 2")
  
  ; insert another key-value pair with a numeric value
  jsonElement = AddJSONMember(jsonObject, "Key 3")
  SetJSONInteger(jsonElement, 3)
  
  ; insert an array into the json object
  jsonArray = AddJSONMember(jsonObject, "Key 4")
  SetJSONArray(jsonArray)
  
  ; insert a value into the array object
  jsonArrayElements = AddJSONElement(jsonArray)
  SetJSONString(jsonArrayElements, "String 1") 
  
  ; repeat the last command to insert more elements into the array
  jsonArrayElements = AddJSONElement(jsonArray)
  SetJSONDouble(jsonArrayElements, 2.2) 
  
  Debug "the JSON object array with two elements:"
  Debug ComposeJSON(#json, #PB_JSON_PrettyPrint) + #CRLF$ 
  
  ; clear & release the json object
  FreeJSON(#json)
  
EndIf

Code: Select all

the JSON object array with two elements:
{
  "Key 1": "Value 1",
  "Key 2": "Value 2",
  "Key 3": 3,
  "Key 4": [
      "String 1",
      2.2
    ]
}
Chaining JSON functions - Inserting more values into the JSON object array

Code: Select all

#json = 0

; create an empty json placeholder
If CreateJSON(#json)
  
  ; sets the created json placeholder as a json object
  jsonObject = SetJSONObject(JSONValue(#json))
  
  ; insert a key-value pair into the json object
  jsonElement = AddJSONMember(jsonObject, "Key 1")
  SetJSONString(jsonElement, "Value 1")
  
  ; insert another key-value pair into the json object
  jsonElement = AddJSONMember(jsonObject, "Key 2")
  SetJSONString(jsonElement, "Value 2")
  
  ; insert another key-value pair with a numeric value
  jsonElement = AddJSONMember(jsonObject, "Key 3")
  SetJSONInteger(jsonElement, 3)
  
  ; insert an array into the json object
  jsonArray = AddJSONMember(jsonObject, "Key 4")
  SetJSONArray(jsonArray)
  
  ; insert a value into the array object
  jsonArrayElements = AddJSONElement(jsonArray)
  SetJSONString(jsonArrayElements, "String 1") 
  
  ; repeat the last command to insert more elements into the array
  jsonArrayElements = AddJSONElement(jsonArray)
  SetJSONDouble(jsonArrayElements, 2.2) 
  
  ; add elements to the array in a loop with a chained syntax
  For i = 3 To 8 Step 2  
    SetJSONInteger(AddJSONElement(jsonArray), i)  
    SetJSONString(AddJSONElement(jsonArray), "String " + Str(i + 1))
  Next i  
  
  Debug "the JSON object with even more array entries:"
  Debug ComposeJSON(#json, #PB_JSON_PrettyPrint) + #CRLF$  
  
  ; clear & release the json object
  FreeJSON(#json)
  
EndIf

Code: Select all

the JSON object with even more array entries:
{
  "Key 1": "Value 1",
  "Key 2": "Value 2",
  "Key 3": 3,
  "Key 4": [
      "String 1",
      2.2,
      3,
      "String 4",
      5,
      "String 6",
      7,
      "String 8"
    ]
}
Inserting another array into the JSON object

Code: Select all

#json = 0

; create an empty json placeholder
If CreateJSON(#json)
  
  ; sets the created json placeholder as a json object
  jsonObject = SetJSONObject(JSONValue(#json))
  
  ; insert a key-value pair into the json object
  jsonElement = AddJSONMember(jsonObject, "Key 1")
  SetJSONString(jsonElement, "Value 1")
  
  ; insert another key-value pair into the json object
  jsonElement = AddJSONMember(jsonObject, "Key 2")
  SetJSONString(jsonElement, "Value 2")
  
  ; insert another key-value pair with a numeric value
  jsonElement = AddJSONMember(jsonObject, "Key 3")
  SetJSONInteger(jsonElement, 3)
  
  ; insert an array into the json object
  jsonArray = AddJSONMember(jsonObject, "Key 4")
  SetJSONArray(jsonArray)
  
  ; insert a value into the array object
  jsonArrayElements = AddJSONElement(jsonArray)
  SetJSONString(jsonArrayElements, "String 1") 
  
  ; repeat the last command to insert more elements into the array
  jsonArrayElements = AddJSONElement(jsonArray)
  SetJSONDouble(jsonArrayElements, 2.2) 
  
  ; add elements to the array in a loop with a chained syntax
  For i = 3 To 8 Step 2  
    SetJSONInteger(AddJSONElement(jsonArray), i)  
    SetJSONString(AddJSONElement(jsonArray), "String " + Str(i + 1))
  Next i  
  
  ; insert another array into the json object
  jsonArray2 = AddJSONMember(jsonObject, "Key 5")
  SetJSONArray(jsonArray2)
  
  Debug "the JSON object with another new empty array object (Key 5):"
  Debug ComposeJSON(#json, #PB_JSON_PrettyPrint) + #CRLF$ 
  
  ; clear & release the json object
  FreeJSON(#json)
  
EndIf

Code: Select all

the JSON object with another new empty array object (Key 5):
{
  "Key 1": "Value 1",
  "Key 2": "Value 2",
  "Key 3": 3,
  "Key 4": [
      "String 1",
      2.2,
      3,
      "String 4",
      5,
      "String 6",
      7,
      "String 8"
    ],
  "Key 5": []
}
Inserting a JSON object into the JSON object array

Code: Select all

#json = 0

; create an empty json placeholder
If CreateJSON(#json)
  
  ; sets the created json placeholder as a json object
  jsonObject = SetJSONObject(JSONValue(#json))
  
  ; insert a key-value pair into the json object
  jsonElement = AddJSONMember(jsonObject, "Key 1")
  SetJSONString(jsonElement, "Value 1")
  
  ; insert another key-value pair into the json object
  jsonElement = AddJSONMember(jsonObject, "Key 2")
  SetJSONString(jsonElement, "Value 2")
  
  ; insert another key-value pair with a numeric value
  jsonElement = AddJSONMember(jsonObject, "Key 3")
  SetJSONInteger(jsonElement, 3)
  
  ; insert an array into the json object
  jsonArray = AddJSONMember(jsonObject, "Key 4")
  SetJSONArray(jsonArray)
  
  ; insert a value into the array object
  jsonArrayElements = AddJSONElement(jsonArray)
  SetJSONString(jsonArrayElements, "String 1") 
  
  ; repeat the last command to insert more elements into the array
  jsonArrayElements = AddJSONElement(jsonArray)
  SetJSONDouble(jsonArrayElements, 2.2) 
  
  ; add elements to the array in a loop with a chained syntax
  For i = 3 To 8 Step 2  
    SetJSONInteger(AddJSONElement(jsonArray), i)  
    SetJSONString(AddJSONElement(jsonArray), "String " + Str(i + 1))
  Next i  
  
  ; insert another array into the json object
  jsonArray2 = AddJSONMember(jsonObject, "Key 5")
  SetJSONArray(jsonArray2)
  
  ; insert a new json object as the array element
  jsonArray2Elements = AddJSONElement(jsonArray2)
  jsonArray2Element = SetJSONObject(jsonArray2Elements)   
  
  Debug "the JSON object with an array containing a json object:"
  Debug ComposeJSON(#json, #PB_JSON_PrettyPrint) + #CRLF$ 
  
  ; clear & release the json object
  FreeJSON(#json)
  
EndIf

Code: Select all

the JSON object with an array containing a JSON object:
{
  "Key 1": "Value 1",
  "Key 2": "Value 2",
  "Key 3": 3,
  "Key 4": [
      "String 1",
      2.2,
      3,
      "String 4",
      5,
      "String 6",
      7,
      "String 8"
    ],
  "Key 5": [
      {}
    ]
}
Inserting key-value pairs into the JSON object in the JSON object array

Code: Select all

#json = 0

; create an empty json placeholder
If CreateJSON(#json)
  
  ; sets the created json placeholder as a json object
  jsonObject = SetJSONObject(JSONValue(#json))
  
  ; insert a key-value pair into the json object
  jsonElement = AddJSONMember(jsonObject, "Key 1")
  SetJSONString(jsonElement, "Value 1")
  
  ; insert another key-value pair into the json object
  jsonElement = AddJSONMember(jsonObject, "Key 2")
  SetJSONString(jsonElement, "Value 2")
  
  ; insert another key-value pair with a numeric value
  jsonElement = AddJSONMember(jsonObject, "Key 3")
  SetJSONInteger(jsonElement, 3)
  
  ; insert an array into the json object
  jsonArray = AddJSONMember(jsonObject, "Key 4")
  SetJSONArray(jsonArray)
  
  ; insert a value into the array object
  jsonArrayElements = AddJSONElement(jsonArray)
  SetJSONString(jsonArrayElements, "String 1") 
  
  ; repeat the last command to insert more elements into the array
  jsonArrayElements = AddJSONElement(jsonArray)
  SetJSONDouble(jsonArrayElements, 2.2) 
  
  ; add elements to the array in a loop with a chained syntax
  For i = 3 To 8 Step 2  
    SetJSONInteger(AddJSONElement(jsonArray), i)  
    SetJSONString(AddJSONElement(jsonArray), "String " + Str(i + 1))
  Next i  
  
  ; insert another array into the json object
  jsonArray2 = AddJSONMember(jsonObject, "Key 5")
  SetJSONArray(jsonArray2)
  
  ; insert a new json object as the array element
  jsonArray2Elements = AddJSONElement(jsonArray2)
  jsonArray2Element = SetJSONObject(jsonArray2Elements)   
  
  ; add key-value pairs into the json array object
  For i =  1 To 3
    jsonElement = AddJSONMember(jsonArray2Element, "Array Key " + Str(i))
    SetJSONString(jsonElement, "Array Value " + Str(i))
  Next i
  
  ; insert an integer value
  jsonElement = AddJSONMember(jsonArray2Element, "Array Key 4")
  SetJSONInteger(jsonElement, 4)
  
  ; insert a double value
  jsonElement = AddJSONMember(jsonArray2Element, "Array Key 5")
  SetJSONDouble(jsonElement, 5.5)
  
  Debug "the JSON object with an array containing a JSON object & values:"
  Debug ComposeJSON(#json, #PB_JSON_PrettyPrint) + #CRLF$
  
  ; clear & release the json object
  FreeJSON(#json)
  
EndIf

Code: Select all

the JSON object with an array containing a JSON object & values:
{
  "Key 1": "Value 1",
  "Key 2": "Value 2",
  "Key 3": 3,
  "Key 4": [
      "String 1",
      2.2,
      3,
      "String 4",
      5,
      "String 6",
      7,
      "String 8"
    ],
  "Key 5": [
      {
        "Array Key 1": "Array Value 1",
        "Array Key 2": "Array Value 2",
        "Array Key 3": "Array Value 3",
        "Array Key 4": 4,
        "Array Key 5": 5.5
      }
    ]
}
Inserting two more JSON objects into the JSON object array

Code: Select all

#json = 0

; create an empty json placeholder
If CreateJSON(#json)
  
  ; sets the created json placeholder as a json object
  jsonObject = SetJSONObject(JSONValue(#json))
  
  ; insert a key-value pair into the json object
  jsonElement = AddJSONMember(jsonObject, "Key 1")
  SetJSONString(jsonElement, "Value 1")
  
  ; insert another key-value pair into the json object
  jsonElement = AddJSONMember(jsonObject, "Key 2")
  SetJSONString(jsonElement, "Value 2")
  
  ; insert another key-value pair with a numeric value
  jsonElement = AddJSONMember(jsonObject, "Key 3")
  SetJSONInteger(jsonElement, 3)
  
  ; insert an array into the json object
  jsonArray = AddJSONMember(jsonObject, "Key 4")
  SetJSONArray(jsonArray)
  
  ; insert a value into the array object
  jsonArrayElements = AddJSONElement(jsonArray)
  SetJSONString(jsonArrayElements, "String 1") 
  
  ; repeat the last command to insert more elements into the array
  jsonArrayElements = AddJSONElement(jsonArray)
  SetJSONDouble(jsonArrayElements, 2.2) 
  
  ; add elements to the array in a loop with a chained syntax
  For i = 3 To 8 Step 2  
    SetJSONInteger(AddJSONElement(jsonArray), i)  
    SetJSONString(AddJSONElement(jsonArray), "String " + Str(i + 1))
  Next i  
  
  ; insert another array into the json object
  jsonArray2 = AddJSONMember(jsonObject, "Key 5")
  SetJSONArray(jsonArray2)
  
  ; insert a new json object as the array element
  jsonArray2Elements = AddJSONElement(jsonArray2)
  jsonArray2Element = SetJSONObject(jsonArray2Elements)   
  
  ; add key-value pairs into the json array object
  For i =  1 To 3
    jsonElement = AddJSONMember(jsonArray2Element, "Array Key " + Str(i))
    SetJSONString(jsonElement, "Array Value " + Str(i))
  Next i
  
  ; insert an integer value
  jsonElement = AddJSONMember(jsonArray2Element, "Array Key 4")
  SetJSONInteger(jsonElement, 4)
  
  ; insert a double value
  jsonElement = AddJSONMember(jsonArray2Element, "Array Key 5")
  SetJSONDouble(jsonElement, 5.5)
  
  ; insert another two new json object as array elements - chained syntax
  jsonArray2Element2 = SetJSONObject(AddJSONElement(jsonArray2))   
  jsonArray2Element3 = SetJSONObject(AddJSONElement(jsonArray2))   
  
  Debug "the JSON object with an array containing three json objects:"
  Debug ComposeJSON(#json, #PB_JSON_PrettyPrint) + #CRLF$
  
  ; clear & release the json object
  FreeJSON(#json)
  
EndIf

Code: Select all

the JSON object with an array containing three json objects:
{
  "Key 1": "Value 1",
  "Key 2": "Value 2",
  "Key 3": 3,
  "Key 4": [
      "String 1",
      2.2,
      3,
      "String 4",
      5,
      "String 6",
      7,
      "String 8"
    ],
  "Key 5": [
      {
        "Array Key 1": "Array Value 1",
        "Array Key 2": "Array Value 2",
        "Array Key 3": "Array Value 3",
        "Array Key 4": 4,
        "Array Key 5": 5.5
      },
      {},
      {}
    ]
}
Inserting additional values to the earlier created nodes & arrays

Code: Select all

#json = 0

; create an empty json placeholder
If CreateJSON(#json)
  
  ; sets the created json placeholder as a json object
  jsonObject = SetJSONObject(JSONValue(#json))
  
  ; insert a key-value pair into the json object
  jsonElement = AddJSONMember(jsonObject, "Key 1")
  SetJSONString(jsonElement, "Value 1")
  
  ; insert another key-value pair into the json object
  jsonElement = AddJSONMember(jsonObject, "Key 2")
  SetJSONString(jsonElement, "Value 2")
  
  ; insert another key-value pair with a numeric value
  jsonElement = AddJSONMember(jsonObject, "Key 3")
  SetJSONInteger(jsonElement, 3)
  
  ; insert an array into the json object
  jsonArray = AddJSONMember(jsonObject, "Key 4")
  SetJSONArray(jsonArray)
  
  ; insert a value into the array object
  jsonArrayElements = AddJSONElement(jsonArray)
  SetJSONString(jsonArrayElements, "String 1") 
  
  ; repeat the last command to insert more elements into the array
  jsonArrayElements = AddJSONElement(jsonArray)
  SetJSONDouble(jsonArrayElements, 2.2) 
  
  ; add elements to the array in a loop with a chained syntax
  For i = 3 To 8 Step 2  
    SetJSONInteger(AddJSONElement(jsonArray), i)  
    SetJSONString(AddJSONElement(jsonArray), "String " + Str(i + 1))
  Next i  
  
  ; insert another array into the json object
  jsonArray2 = AddJSONMember(jsonObject, "Key 5")
  SetJSONArray(jsonArray2)
  
  ; insert a new json object as the array element
  jsonArray2Elements = AddJSONElement(jsonArray2)
  jsonArray2Element = SetJSONObject(jsonArray2Elements)   
  
  ; add key-value pairs into the json array object
  For i =  1 To 3
    jsonElement = AddJSONMember(jsonArray2Element, "Array Key " + Str(i))
    SetJSONString(jsonElement, "Array Value " + Str(i))
  Next i
  
  ; insert an integer value
  jsonElement = AddJSONMember(jsonArray2Element, "Array Key 4")
  SetJSONInteger(jsonElement, 4)
  
  ; insert a double value
  jsonElement = AddJSONMember(jsonArray2Element, "Array Key 5")
  SetJSONDouble(jsonElement, 5.5)
  
  ; insert another two new json object as array elements - chained syntax
  jsonArray2Element2 = SetJSONObject(AddJSONElement(jsonArray2))   
  jsonArray2Element3 = SetJSONObject(AddJSONElement(jsonArray2))   
  
  ; add elements to the second json object in the array
  jsonElement = AddJSONMember(jsonArray2Element2, "Array Key 1")
  SetJSONString(jsonElement, "Array Value 1")
  
  ; add elements to the third json object in the array
  jsonElement = AddJSONMember(jsonArray2Element3, "Array Key 1")
  SetJSONString(jsonElement, "Array Value 1")
  jsonElement = AddJSONMember(jsonArray2Element3, "Array Key 2")
  SetJSONString(jsonElement, "Array Value 2")
  
  ; add more elements to the first json object in the array
  jsonElement = AddJSONMember(jsonArray2Element, "Array Key 6")
  SetJSONString(jsonElement, "Array Value 6")
  
  ; add more elements to the first array in the json object
  jsonArrayElement = AddJSONElement(jsonArray)
  SetJSONString(jsonArrayElement, "String 9")  
  
  Debug "the final JSON object:"
  Debug ComposeJSON(#json, #PB_JSON_PrettyPrint) + #CRLF$
  
  ; clear & release the json object
  FreeJSON(#json)
  
EndIf

Code: Select all

the final JSON object:
{
  "Key 1": "Value 1",
  "Key 2": "Value 2",
  "Key 3": 3,
  "Key 4": [
      "String 1",
      2.2,
      3,
      "String 4",
      5,
      "String 6",
      7,
      "String 8",
      "String 9"
    ],
  "Key 5": [
      {
        "Array Key 1": "Array Value 1",
        "Array Key 2": "Array Value 2",
        "Array Key 3": "Array Value 3",
        "Array Key 4": 4,
        "Array Key 5": 5.5,
        "Array Key 6": "Array Value 6"
      },
      {
        "Array Key 1": "Array Value 1"
      },
      {
        "Array Key 1": "Array Value 1",
        "Array Key 2": "Array Value 2"
      }
    ]
}
Saving the JSON object output to file (complete code for Part 1)

Code: Select all

#json = 0

; create an empty json placeholder
If CreateJSON(#json)
  
  ; sets the created json placeholder as a json object
  jsonObject = SetJSONObject(JSONValue(#json))
  
  ; insert a key-value pair into the json object
  jsonElement = AddJSONMember(jsonObject, "Key 1")
  SetJSONString(jsonElement, "Value 1")
  
  ; insert another key-value pair into the json object
  jsonElement = AddJSONMember(jsonObject, "Key 2")
  SetJSONString(jsonElement, "Value 2")
  
  ; insert another key-value pair with a numeric value
  jsonElement = AddJSONMember(jsonObject, "Key 3")
  SetJSONInteger(jsonElement, 3)
  
  ; insert an array into the json object
  jsonArray = AddJSONMember(jsonObject, "Key 4")
  SetJSONArray(jsonArray)
  
  ; insert a value into the array object
  jsonArrayElements = AddJSONElement(jsonArray)
  SetJSONString(jsonArrayElements, "String 1") 
  
  ; repeat the last command to insert more elements into the array
  jsonArrayElements = AddJSONElement(jsonArray)
  SetJSONDouble(jsonArrayElements, 2.2) 
  
  ; add elements to the array in a loop with a chained syntax
  For i = 3 To 8 Step 2  
    SetJSONInteger(AddJSONElement(jsonArray), i)  
    SetJSONString(AddJSONElement(jsonArray), "String " + Str(i + 1))
  Next i  
  
  ; insert another array into the json object
  jsonArray2 = AddJSONMember(jsonObject, "Key 5")
  SetJSONArray(jsonArray2)
  
  ; insert a new json object as the element
  jsonArray2Elements = AddJSONElement(jsonArray2)
  jsonArray2Element = SetJSONObject(jsonArray2Elements)   
  
  ; add key-value pairs into the json array object
  For i =  1 To 3
    jsonElement = AddJSONMember(jsonArray2Element, "Array Key " + Str(i))
    SetJSONString(jsonElement, "Array Value " + Str(i))
  Next i
  
  ; inser an integer value
  jsonElement = AddJSONMember(jsonArray2Element, "Array Key 4")
  SetJSONInteger(jsonElement, 4)
  
  ; insert a double value
  jsonElement = AddJSONMember(jsonArray2Element, "Array Key 5")
  SetJSONDouble(jsonElement, 5.5)
  
  ; insert another two new json object as array elements - chained syntax
  jsonArray2Element2 = SetJSONObject(AddJSONElement(jsonArray2))   
  jsonArray2Element3 = SetJSONObject(AddJSONElement(jsonArray2))   
  
  ; add elements to the second json object in the array
  jsonElement = AddJSONMember(jsonArray2Element2, "Array Key 1")
  SetJSONString(jsonElement, "Array Value 1")
  
  ; add elements to the third json object in the array
  jsonElement = AddJSONMember(jsonArray2Element3, "Array Key 1")
  SetJSONString(jsonElement, "Array Value 1")
  jsonElement = AddJSONMember(jsonArray2Element3, "Array Key 2")
  SetJSONString(jsonElement, "Array Value 2")
  
  ; add more elements to the first json object in the array
  jsonElement = AddJSONMember(jsonArray2Element, "Array Key 6")
  SetJSONString(jsonElement, "Array Value 6")
  
  ; add more elements to the first array in the json object
  jsonArrayElement = AddJSONElement(jsonArray)
  SetJSONString(jsonArrayElement, "String 9")  
  
  ; save the json object output to file - ensure file path
  If SaveJSON(#json, "jsonFile.txt", #PB_JSON_PrettyPrint)
    Debug "JSON object output saved to jsonFile.txt."
  EndIf
  
  ; clear & release the json object
  FreeJSON(#json)
  
EndIf

Code: Select all

JSON object output saved to jsonFile.txt
PART 2: READING JSON DATA

Reading JSON object data from file

Code: Select all

#json = 0

; load json object data from file - ensure file path
If LoadJSON(#json, "jsonFile.txt")
  
  Debug "the JSON object data from file:"
  Debug ComposeJSON(#json, #PB_JSON_PrettyPrint)
  
  ; clear & release the json object
  FreeJSON(#json)
  
EndIf

Code: Select all

 the JSON object data from file:
{
  "Key 1": "Value 1",
  "Key 2": "Value 2",
  "Key 3": 3,
  "Key 4": [
      "String 1",
      2.2,
      3,
      "String 4",
      5,
      "String 6",
      7,
      "String 8",
      "String 9"
    ],
  "Key 5": [
      {
        "Array Key 1": "Array Value 1",
        "Array Key 2": "Array Value 2",
        "Array Key 3": "Array Value 3",
        "Array Key 4": 4,
        "Array Key 5": 5.5,
        "Array Key 6": "Array Value 6"
      },
      {
        "Array Key 1": "Array Value 1"
      },
      {
        "Array Key 1": "Array Value 1",
        "Array Key 2": "Array Value 2"
      }
    ]
}
Reading JSON object data keys and string values

Code: Select all

#json = 0

; load json object data from file
If LoadJSON(#json, "jsonFile.txt")
  
  ; get the json object value
  jsonObjectValue = JSONValue(#json)
  
  ; retrieve the members of the json object
  If ExamineJSONMembers(jsonObjectValue)
    
    Debug "displaying JSON object members with string values only:"
    
    ; iterate through the members of the json object
    While NextJSONMember(jsonObjectValue)
      
      ; display only members with values of string types
      If JSONType(JSONMemberValue(jsonObjectValue)) = #PB_JSON_String

        Debug "> " + JSONMemberKey(jsonObjectValue) + " = " + 
              GetJSONString(JSONMemberValue(jsonObjectValue))

      EndIf
      
    Wend
    
  EndIf
  
  ; clear & release the json object
  FreeJSON(#json)
  
EndIf

Code: Select all

displaying JSON object members with string values only:
> Key 1 = Value 1
> Key 2 = Value 2
Reading JSON object data keys and numerical values

Code: Select all

#json = 0

; load json object data from file
If LoadJSON(#json, "jsonFile.txt")
  
  ; get the json object value
  jsonObjectValue = JSONValue(#json)
  
  ; retrieve the members of the json object
  If ExamineJSONMembers(jsonObjectValue)
    
    Debug "displaying JSON object members with numerical values only:"
    
    ; iterate through the members of the json object
    While NextJSONMember(jsonObjectValue)
      
      ; display only members with values of numerical types
      If JSONType(JSONMemberValue(jsonObjectValue)) = #PB_JSON_Number

        Debug "> " + JSONMemberKey(jsonObjectValue) + " = " + 
              Str(GetJSONDouble(JSONMemberValue(jsonObjectValue)))

      EndIf
      
    Wend
    
  EndIf
  
  ; clear & release the json object
  FreeJSON(#json)
  
EndIf

Code: Select all

displaying JSON object members with numerical values only:
> Key 3 = 3
Reading JSON object data keys and array values

Code: Select all

#json = 0

; load json object data from file
If LoadJSON(#json, "jsonFile.txt")
  
  ; get the json object value
  jsonObjectValue = JSONValue(#json)
  
  ; retrieve the members of the json object
  If ExamineJSONMembers(jsonObjectValue)
    
    Debug "displaying JSON object members with array values only:"
    
    ; iterate through the members of the json object
    While NextJSONMember(jsonObjectValue)
      
      ; display only members with values of array types
      If JSONType(JSONMemberValue(jsonObjectValue)) = #PB_JSON_Array

        Debug "> " + JSONMemberKey(jsonObjectValue) + " = Array with size " + 
              Str(JSONArraySize(JSONMemberValue(jsonObjectValue)))

      EndIf
      
    Wend
    
  EndIf
  
  ; clear & release the json object
  FreeJSON(#json)
  
EndIf

Code: Select all

displaying JSON object members with array values only:
> Key 4 = Array with size 9
> Key 5 = Array with size 3
Reading JSON object data keys, array values, and its string elements

Code: Select all

#json = 0

; load json object data from file
If LoadJSON(#json, "jsonFile.txt")
  
  ; get the json object value
  jsonObjectValue = JSONValue(#json)
  
  ; retrieve the members of the json object
  If ExamineJSONMembers(jsonObjectValue)
    
    Debug "displaying JSON object members with array values only:"
    
    ; iterate through the members of the json object
    While NextJSONMember(jsonObjectValue)
      
      ; display only members with values of array types
      If JSONType(JSONMemberValue(jsonObjectValue)) = #PB_JSON_Array
        
        ;get the size of the array member
        jArraySize = JSONArraySize(JSONMemberValue(jsonObjectValue))
        
        Debug "> " + JSONMemberKey(jsonObjectValue) + 
              " = Array with size " + Str(jArraySize)  
        
        Debug "   displaying array member string elements only:"

        ; iterate through the elements of the array member
        For i = 0 To (jArraySize - 1) 
          
          ; extract the iterating element from the array
          jsonArrayElement = GetJSONElement(JSONMemberValue(jsonObjectValue), i)
          
          ; display only elements with values of string types
          If JSONType(jsonArrayElement) = #PB_JSON_String
            
            Debug "   array element " + Str(i) + " = " + GetJSONString(jsonArrayElement)
            
          EndIf
          
        Next i 
        
      EndIf
      
    Wend
    
  EndIf
  
  ; clear & release the json object
  FreeJSON(#json)
  
EndIf

Code: Select all

displaying JSON object members with array values only:
> Key 4 = Array with size 9
   displaying array member string elements only:
   array element 0 = String 1
   array element 3 = String 4
   array element 5 = String 6
   array element 7 = String 8
   array element 8 = String 9
> Key 5 = Array with size 3
   displaying array member string elements only:
Reading JSON object data keys, array values, and its numerical elements

Code: Select all

#json = 0

; load json object data from file
If LoadJSON(#json, "jsonFile.txt")
  
  ; get the json object value
  jsonObjectValue = JSONValue(#json)
  
  ; retrieve the members of the json object
  If ExamineJSONMembers(jsonObjectValue)
    
    Debug "displaying JSON object members with array values only:"
    
    ; iterate through the members of the json object
    While NextJSONMember(jsonObjectValue)
      
      ; display only members with values of array types
      If JSONType(JSONMemberValue(jsonObjectValue)) = #PB_JSON_Array
        
        ;get the size of the array member
        jArraySize = JSONArraySize(JSONMemberValue(jsonObjectValue))
        
        Debug "> " + JSONMemberKey(jsonObjectValue) + 
              " = Array with size " + Str(jArraySize)  
        
        Debug "   displaying array member numerical elements only:"

        ; iterate through the elements of the array member
        For i = 0 To (jArraySize - 1) 
          
          ; extract the iterating element from the array
          jsonArrayElement = GetJSONElement(JSONMemberValue(jsonObjectValue), i)
          
          ; display only elements with values of numerical types
          If JSONType(jsonArrayElement) = #PB_JSON_Number
            
            Debug "   array element " + Str(i) + " = " + GetJSONDouble(jsonArrayElement)
            
          EndIf
          
        Next i 
        
      EndIf
      
    Wend
    
  EndIf
  
  ; clear & release the json object
  FreeJSON(#json)
  
EndIf

Code: Select all

displaying JSON object members with array values only:
> Key 4 = Array with size 9
   displaying array member numerical elements only:
   array element 1 = 2.2
   array element 2 = 3
   array element 4 = 5
   array element 6 = 7
> Key 5 = Array with size 3
   displaying array member numerical elements only:
In the last few snippets, it's clear that the value type of each JSON object and JSON array element must be predetermined before they could be safely extracted and displayed. Furthermore, since JSON objects can be nested almost indefinitely, these drill-down checks could prove endless.

Therefore, these extraction and validation routines should be performed recursively through the JSON structure with the use of procedures. The following snippet automatically iterates through any JSON data object, extracts the key names of each node, validates the value types, and displays the results in a key-value pair format.


Reading, validating, and extracting all values from a JSON data object (complete code for Part 2)

Code: Select all

#json = 0

Declare jsonRetrieveMembers(jsonObjectValue)
Declare jsonArrayRetrieveElements(jsonObjectValue)

Procedure jsonRetrieveMembers(jsonObjectValue)
  
  ; retrieve the json object members
  If ExamineJSONMembers(jsonObjectValue)
    
    ; iterate through the json object members 
    While NextJSONMember(jsonObjectValue)
      
      ; determine the type of value stored in the member
      jsonValueType = JSONType(JSONMemberValue(jsonObjectValue))
      
      ; retrieve the key name of the member
      jsonMemberKeyName.s = JSONMemberKey(jsonObjectValue)
      
      ; retrieve the key-value of each member according
      ; to the respective data type and display them
      If jsonValueType = #PB_JSON_String
        
        ; retrieve & display the string value of the member 
        Debug " " + jsonMemberKeyName + " = " + 
              GetJSONString(JSONMemberValue(jsonObjectValue))
        
      ElseIf jsonValueType = #PB_JSON_Number
        
        ; retrieve & display the numeric value of the member 
        Debug " " + jsonMemberKeyName + " = " + 
              GetJSONDouble(JSONMemberValue(jsonObjectValue))       
        
      ElseIf jsonValueType = #PB_JSON_Object
        
        Debug " " + jsonMemberKeyName + " = JSON Object"
        jsonRetrieveMembers(JSONMemberValue(jsonObjectValue))
        
      ElseIf jsonValueType = #PB_JSON_Array
        
        jsonArrayRetrieveElements(jsonObjectValue)
        
      EndIf      
      
    Wend
    
  EndIf
  
EndProcedure

Procedure jsonArrayRetrieveElements(jsonObjectValue)
  
  ; retrieve the key name of the member
  jsonMemberKeyName.s = JSONMemberKey(jsonObjectValue)
  
  ; get the size of the array member
  jArraySize = JSONArraySize(JSONMemberValue(jsonObjectValue))
  Debug " " + jsonMemberKeyName + " = Array of size " + Str(jArraySize)
  
  ; get the elements of the array member
  For i = 0 To (jArraySize - 1) 
    
    jsonArrayElement = GetJSONElement(JSONMemberValue(jsonObjectValue), i)
    jsonValueType = JSONType(jsonArrayElement)          
    
    If jsonValueType = #PB_JSON_String
      
      Debug " > array element " + Str(i) + " = " + GetJSONString(jsonArrayElement)
      
    ElseIf jsonValueType = #PB_JSON_Number
      
      Debug " > array element " + Str(i) + " = " + Str(GetJSONDouble(jsonArrayElement))
      
    ElseIf jsonValueType = #PB_JSON_Array
      
      Debug " > array element " + Str(i) + " = JSON Array"
      jsonArrayRetrieveElements(jsonArrayElement)
      
    ElseIf jsonValueType = #PB_JSON_Object
      
      Debug " > array element " + Str(i) + " = JSON Object"            
      jsonRetrieveMembers(jsonArrayElement)
      
    EndIf
    
  Next i  
  
EndProcedure

; load json object data from file
If LoadJSON(#json, "jsonFile.txt")
  
  Debug "all key-value data in the json object:"
  
  ; get the values of the json object
  jsonObjectValue = JSONValue(#json)
  
  jsonRetrieveMembers(jsonObjectValue)
  
  ; clear & release the json object
  FreeJSON(#json)
  
EndIf

Code: Select all

all key-value data in the json object:
 Key 1 = Value 1
 Key 2 = Value 2
 Key 3 = 3
 Key 4 = Array of size 9
 > array element 0 = String 1
 > array element 1 = 2
 > array element 2 = 3
 > array element 3 = String 4
 > array element 4 = 5
 > array element 5 = String 6
 > array element 6 = 7
 > array element 7 = String 8
 > array element 8 = String 9
 Key 5 = Array of size 3
 > array element 0 = JSON Object
 Array Key 1 = Array Value 1
 Array Key 2 = Array Value 2
 Array Key 3 = Array Value 3
 Array Key 4 = 4
 Array Key 5 = 5.5
 Array Key 6 = Array Value 6
 > array element 1 = JSON Object
 Array Key 1 = Array Value 1
 > array element 2 = JSON Object
 Array Key 1 = Array Value 1
 Array Key 2 = Array Value 2
And those are the fundamental methods and concepts of using PureBasic's JSON functions. :D

A practical example of these functions in action can be found in this little utility:

> SQLite Database to JSON File Converter
Texas Instruments TI-99/4A Home Computer: the first home computer with a 16bit processor, crammed into an 8bit architecture. Great hardware - Poor design - Wonderful BASIC engine. And it could talk too!
User avatar
Tenaja
Addict
Addict
Posts: 1822
Joined: Tue Nov 09, 2010 10:15 pm

Re: PureBasic JSON: A Quick Tutorial

Post by Tenaja »

Thanks for taking the time to post that.
User avatar
blueb
Addict
Addict
Posts: 918
Joined: Sat Apr 26, 2003 2:15 pm
Location: Cuernavaca, Mexico

Re: PureBasic JSON: A Quick Tutorial

Post by blueb »

Thanks Syed,

It's obvious you did a lot of work to present this properly... it was very helpful.

This set of lessons should be added as a 'sticky' like your PureBasic Modules tutorials. :mrgreen:
- It was too lonely at the top.

Current Machine: Win 10 Pro 64-bit, Dual Xeon E5-2670, 64 gigs ram, Geforce GTX 1660 Ti w/6 gigs ram
User avatar
TI-994A
Addict
Addict
Posts: 2490
Joined: Sat Feb 19, 2011 3:47 am
Location: Singapore

Re: PureBasic JSON: A Quick Tutorial

Post by TI-994A »

Tenaja & blueb, thank you for your kind words. I truly hope that it will prove helpful. :D
Texas Instruments TI-99/4A Home Computer: the first home computer with a 16bit processor, crammed into an 8bit architecture. Great hardware - Poor design - Wonderful BASIC engine. And it could talk too!
User avatar
Andre
PureBasic Team
PureBasic Team
Posts: 1877
Joined: Fri Apr 25, 2003 6:14 pm
Location: Germany (Saxony, Deutscheinsiedel)
Contact:

Re: PureBasic JSON: A Quick Tutorial

Post by Andre »

Looks very good, thank you! :D

Would be worth having it in the 'Beginners' chapter of the PB manual... 8)
Bye,
...André
(PureBasicTeam::Docs & Support - PureArea.net | Order:: PureBasic | PureVisionXP)
User avatar
TI-994A
Addict
Addict
Posts: 2490
Joined: Sat Feb 19, 2011 3:47 am
Location: Singapore

Re: PureBasic JSON: A Quick Tutorial

Post by TI-994A »

Thanks Andre.
Texas Instruments TI-99/4A Home Computer: the first home computer with a 16bit processor, crammed into an 8bit architecture. Great hardware - Poor design - Wonderful BASIC engine. And it could talk too!
Post Reply