|
<< Click to Display Table of Contents >> Navigation: 3. Script Language > JSON - Parser > Text-Operations > PSJ. - JSON Operations |
SPR Script Language
PSJ.ExtractNum
Extracts a number from JSON as a string.
Intention
The PSJ.ExtractNum command in SPR reads a JSON string ($$JSON) and extracts a number from a specific location ($$PATH), returning it as a string in an optional variable ($$RET). It’s like asking your robot to look into a JSON ledger, find a number at a given spot—like an age or count—and write it down as text for you.
For example, from {"data":{"age":30}}, it extracts "30" from the "age" field under "data".
Illustration
📝 Extract: PSJ.ExtractNum|{"count":42}|count|$$NUM sets $$NUM to "42".
📝 Nested: PSJ.ExtractNum|{"data":{"size":15}}|data.size|$$VAL sets $$VAL to "15".
Syntax
PSJ.ExtractNum|$$JSON|$$PATH[|$$RET]
Parameter Explanation
P1 - $$JSON - (Variable, String)
The JSON string to parse (e.g., $$JSON as "{\"data\":{\"age\":30}}"). Required.
P2 - $$PATH - (Variable, String)
The dot-separated path to the number value (e.g., $$PATH as "data.age"). Required.
P3 - $$RET - (Variable, String, Optional)
The variable to store the extracted number as a string (e.g., $$RET as "$$NUM"). If omitted, the string is returned but not stored.
Technical Background
This command calls W_JSON_ExtractNumber, which parses a JSON string (jsonText) and extracts a number at path as a string. It returns the number as a string (e.g., "30" from {"data":{"age":30}} with path "data.age") or an empty string if an error occurs (e.g., invalid JSON or path). Internally, it uses W_JSON_ParseString to create a handle, W_JSON_GetNumberByPath to extract the value, and W_JSON_FreeHandle to clean up. Errors set gLastJSONError and gLastJSONErrorMsg. No handle is returned, so no freeing is needed by the caller.
Examples
'***********************************
' Sample 1: Extract Simple Number
PSJ.ExtractNum|{"count":42}|count|$$NUM
' Print the extracted number
PRT.Number: $$NUM
MBX.Ready
'***********************************
' Sample 2: Extract from Nested Path
PSJ.ExtractNum|{"data":{"size":15}}|data.size|$$VAL
' Print the extracted number
PRT.Number: $$VAL
MBX.Ready
'***********************************
' Sample 3: No Return Variable
PSJ.ExtractNum|{"value":100}|value
' Number returned but not stored
MBX.Ready
Remarks
- Returns the number as a string; no handle is created.
- Returns an empty string if the path is invalid or not a number.
- Use PSJ.ErrCode to check errors if the result is empty.
Limitations
- $$JSON must be valid JSON.
- $$PATH must point to a number value, or an empty string is returned.
See also: