|
<< Click to Display Table of Contents >> Navigation: 3. Script Language > JSON - Parser > Parser-Operations > !Node Operations > PSJ. - JSON Operations |
SPR Script Language
PSJ.GetType
Retrieves the type of a node at a specified path in a JSON document.
Intention
The PSJ.GetType command in SPR identifies the type of a JSON node at a given path ($$PATH) within a document specified by its handle ($$DHA). It returns a numeric value representing the node’s type (e.g., string, number, object), which you can optionally store in a variable (e.g., $$RET). This is useful for checking data types before performing operations like PSJ.GetNum or PSJ.GetObj.
Think of it as asking your robot, “What kind of thing is at this JSON spot?”—and it replies with a number like 2 for a number or 6 for an object, placing it on the Top of Stack (TOS) or in your variable.
Illustration
Consider this JSON document:
{"data": {"id": 42, "active": true}}
- 🔍 PSJ.GetType|$$DHA|data.id|$$RET stores "2" (number type) in $$RET.
- 🔍 PSJ.GetType|$$DHA|data.active places "3" (boolean type) on TOS.
Syntax
PSJ.GetType|$$DHA|$$PATH[|$$RET]
Parameter Explanation
P1 - $$DHA - (Variable, Numeric)
The document handle identifying the JSON data (e.g., $$DHA as "123"). Required. Obtained from PSJ.Parse or PSJ.LoadFile.
P2 - $$PATH - (Variable, String)
The path to the node whose type you want (e.g., $$PATH as "data.id"). Required. Use dot notation (e.g., "user.name") or leave blank for the root.
P3 - $$RET - (Variable, String, Optional)
The variable to store the type as a string (e.g., $$RET). If omitted, the result is returned on Top of Stack (TOS).
Examples
'***********************************
' PSJ.GetType - Sample 1: Get Type of a Number
'***********************************
PSJ.Parse|{"value": 123}|$$DHA
PSJ.GetType|$$DHA|value|$$RET
MBX.Type: $$RET ' Displays "2" (number)
PSJ.Free|$$DHA
MBX.Ready
'
'***********************************
' PSJ.GetType - Sample 2: Get Type of an Object
'***********************************
PSJ.Parse|{"user": {"name": "Bob"}}|$$DHA
PSJ.GetType|$$DHA|user|$$RET
PRT.Type: $$RET ' Prints "6" (object)
PSJ.Free|$$DHA
MBX.Ready
'
'***********************************
' PSJ.GetType - Sample 3: Result on TOS
'***********************************
PSJ.Parse|{"flag": true}|$$DHA
PSJ.GetType|$$DHA|flag
' Places "3" (boolean) on Top of Stack (TOS)
PSJ.Free|$$DHA
MBX.Ready
'
Remarks
- Returns a numeric type code as a string: "1" (string), "2" (number), "3" (boolean), "4" (null), "5" (array), "6" (object), or "0" (error or not found).
- Works for all JSON node types, unlike type-specific commands like PSJ.GetNum or PSJ.GetObj.
- Use this to validate node types before calling other PSJ commands.
Limitations
- Requires a valid document handle; invalid handles return "0".
- Returns "0" if the path doesn’t exist, which may be ambiguous (error vs. invalid path).
See also: