PureBasic JSON: A Quick Tutorial

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

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! Please visit my YouTube Channel :D
User avatar
Tenaja
Addict
Addict
Posts: 1949
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: 1044
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.

System : PB 6.10 LTS (x64) and Win Pro 11 (x64)
Hardware: AMD Ryzen 9 5900X w/64 gigs Ram, AMD RX 6950 XT Graphics w/16gigs Mem
User avatar
TI-994A
Addict
Addict
Posts: 2512
Joined: Sat Feb 19, 2011 3:47 am
Location: Singapore
Contact:

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! Please visit my YouTube Channel :D
User avatar
Andre
PureBasic Team
PureBasic Team
Posts: 2071
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: 2512
Joined: Sat Feb 19, 2011 3:47 am
Location: Singapore
Contact:

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! Please visit my YouTube Channel :D
User avatar
Dreamland Fantasy
Enthusiast
Enthusiast
Posts: 335
Joined: Fri Jun 11, 2004 9:35 pm
Location: Glasgow, UK
Contact:

Re: PureBasic JSON: A Quick Tutorial

Post by Dreamland Fantasy »

Very nice tutorial TI-994A. :) Very helpful as I'm still trying to get my head around dealing with JSON.

One thing that I'm struggling with though is how to work out how deep in the JSON hierarchy an element is so that the parent items can be worked out.

Code: Select all

{
    "media": {
        "image": {
            "bitmap": [
                ".bmp",
                ".gif",
                ".ico",
                ".jpeg",
                ".jpg",
                ".png",
                ".tga",
                ".tif",
                ".tiff"
             ]
        }
    }
}
In the above JSON data, how can I tell if e.g. '.jpg' would come under 'media/image/bitmap/.jpg' and not just 'image/bitmap/.jpg'?

Code: Select all

all key-value data in the json object:
 media = JSON Object
 image = JSON Object
 bitmap = Array of size 9
 > array element 0 = .bmp
 > array element 1 = .gif
 > array element 2 = .ico
 > array element 3 = .jpeg
 > array element 4 = .jpg
 > array element 5 = .png
 > array element 6 = .tga
 > array element 7 = .tif
 > array element 8 = .tiff
Kind regards,

Francis
Quin
Enthusiast
Enthusiast
Posts: 327
Joined: Thu Mar 31, 2022 7:03 pm
Location: United States
Contact:

Re: PureBasic JSON: A Quick Tutorial

Post by Quin »

Unfortunately the way you have to do this is slightly messy, I tend to wrap it up into a macro. You have to chain calls to the JSON functions, like so:

Code: Select all

GetJSONString(GetJSONMember(GetJSONMember(GetJSONMember(JSONValue(0), "media"), "image"), "bitmap")
I don't think that's technically syntactically correct (writing from a system without PB to install and test on at the moment) but it should get you on the right path at least.
Dreamland Fantasy wrote: Wed Mar 13, 2024 12:11 am Very nice tutorial TI-994A. :) Very helpful as I'm still trying to get my head around dealing with JSON.

One thing that I'm struggling with though is how to work out how deep in the JSON hierarchy an element is so that the parent items can be worked out.

Code: Select all

{
    "media": {
        "image": {
            "bitmap": [
                ".bmp",
                ".gif",
                ".ico",
                ".jpeg",
                ".jpg",
                ".png",
                ".tga",
                ".tif",
                ".tiff"
             ]
        }
    }
}
In the above JSON data, how can I tell if e.g. '.jpg' would come under 'media/image/bitmap/.jpg' and not just 'image/bitmap/.jpg'?

Code: Select all

all key-value data in the json object:
 media = JSON Object
 image = JSON Object
 bitmap = Array of size 9
 > array element 0 = .bmp
 > array element 1 = .gif
 > array element 2 = .ico
 > array element 3 = .jpeg
 > array element 4 = .jpg
 > array element 5 = .png
 > array element 6 = .tga
 > array element 7 = .tif
 > array element 8 = .tiff
Kind regards,

Francis
PB v5.40/6.10, Windows 10 64-bit.
16-core AMD Ryzen 9 5950X, 128 GB DDR5.
User avatar
Dreamland Fantasy
Enthusiast
Enthusiast
Posts: 335
Joined: Fri Jun 11, 2004 9:35 pm
Location: Glasgow, UK
Contact:

Re: PureBasic JSON: A Quick Tutorial

Post by Dreamland Fantasy »

Quin wrote: Wed Mar 13, 2024 4:03 am Unfortunately the way you have to do this is slightly messy, I tend to wrap it up into a macro. You have to chain calls to the JSON functions, like so:

Code: Select all

GetJSONString(GetJSONMember(GetJSONMember(GetJSONMember(JSONValue(0), "media"), "image"), "bitmap")
I don't think that's technically syntactically correct (writing from a system without PB to install and test on at the moment) but it should get you on the right path at least.
Thanks for that, although I'm still confused as to how I can get the information I need.

It's probably just me, but using JSON seems to be more complicated that it needs to be. :oops:

Kind regards,

Francis
Quin
Enthusiast
Enthusiast
Posts: 327
Joined: Thu Mar 31, 2022 7:03 pm
Location: United States
Contact:

Re: PureBasic JSON: A Quick Tutorial

Post by Quin »

Sorry, I'll try again.
In a lot of projects where I need JSON parsing, I have macros that look like this:

Code: Select all

Macro JString(Value)
  GetJSONString(GetJSONMember(JSONValue(0), Value))
EndMacro
This macro gets a string with the given key from the top-level of the JSON. The JSONValue(0) call tells the compiler what JSON object you're interested in. From the docs:
Returns the value of the specified #JSON data. The type of the value can be checked with JSONType().
More specifically than "the compiler", it tells the JSONMember() function where to pull its value from. The JSONMember() function:
Return the JSON object member with the given Key$ of a JSON value of type#PB_JSON_Object.
So this gets us a raw JSON value. But we now need to actually get a value out of it! PureBasic has no generic/any type (i.e. a type that can hold any variable), so we have specific functions for each type. In this case, we care about strings, as you can see from checking the JSONType() function.
Syntax
Result$ = GetJSONString(JSONValue)
Description
Return the value of a JSON value of type#PB_JSON_String as a string.
Parameters
JSONValue
The JSON value. The value must be of type #PB_JSON_String.
This is exactly what we want. GetJSONMember() returns a JSON value, as you remember from earlier.
This gets even nicer when you notice that GetJSONMember() also expects a JSON value. This means we can nest, like I showed in my earlier example:
Quin wrote: GetJSONString(GetJSONMember(GetJSONMember(GetJSONMember(JSONValue(0), "media"), "image"), "bitmap")
I'd highly recommend looking through the complete documentation of the JSON library, and trying to write some macros to make this easier for yourself. And, of course, ask here on the forums if you get stuck :)
Dreamland Fantasy wrote: Wed Mar 13, 2024 8:07 pm
Quin wrote: Wed Mar 13, 2024 4:03 am Unfortunately the way you have to do this is slightly messy, I tend to wrap it up into a macro. You have to chain calls to the JSON functions, like so:

Code: Select all

GetJSONString(GetJSONMember(GetJSONMember(GetJSONMember(JSONValue(0), "media"), "image"), "bitmap")
I don't think that's technically syntactically correct (writing from a system without PB to install and test on at the moment) but it should get you on the right path at least.
Thanks for that, although I'm still confused as to how I can get the information I need.

It's probably just me, but using JSON seems to be more complicated that it needs to be. :oops:

Kind regards,

Francis
PB v5.40/6.10, Windows 10 64-bit.
16-core AMD Ryzen 9 5950X, 128 GB DDR5.
Post Reply