|
<< Click to Display Table of Contents >> Navigation: 3. Script Language > JSON - Parser > Text-Operations > PSJ. - JSON Operations |
SPR Script Language
PSJ.ExtractStr
Extracts a string value from JSON by path.
Intention
The PSJ.ExtractStr command in SPR reads a JSON string ($$JSON) and pulls out a string value from a specific location ($$PATH), storing it in an optional variable ($$RET). It’s like asking your robot to open a JSON notebook, find a labeled entry—like a name or message—and copy the text for you.
For example, from {"data":{"user":"Alice"}}, it extracts "Alice" from the "user" field under "data".
Illustration
📝 Extract: PSJ.ExtractStr|{"name":"Bob"}|name|$$VAL sets $$VAL to "Bob".
📝 Nested: PSJ.ExtractStr|{"info":{"title":"Hi"}}|info.title|$$TXT sets $$TXT to "Hi".
Syntax
PSJ.ExtractStr|$$JSON|$$PATH[|$$RET]
Parameter Explanation
P1 - $$JSON - (Variable, String)
The JSON string to parse (e.g., $$JSON as "{\"data\":{\"user\":\"Alice\"}}"). Required.
P2 - $$PATH - (Variable, String)
The dot-separated path to the string value (e.g., $$PATH as "data.user"). Required.
P3 - $$RET - (Variable, String, Optional)
The variable to store the extracted string (e.g., $$RET as "$$VAL"). If omitted, the string is returned but not stored.
Technical Background
This command calls W_JSON_ExtractString, which parses a JSON string (jsonText) and extracts a string at path. It returns the string (e.g., "Alice" from {"data":{"user":"Alice"}} with path "data.user") 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_GetStringByPath 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 String
PSJ.ExtractStr|{"name":"Bob"}|name|$$VAL
' Print the extracted string
PRT.String: $$VAL
MBX.Ready
'***********************************
' Sample 2: Extract from Nested Path
PSJ.ExtractStr|{"info":{"title":"Hi"}}|info.title|$$TXT
' Print the extracted string
PRT.String: $$TXT
MBX.Ready
'***********************************
' Sample 3: No Return Variable
PSJ.ExtractStr|{"msg":"Hello"}|msg
' String returned but not stored
MBX.Ready
Remarks
- Returns the string value directly; no handle is created.
- Returns an empty string if the path is invalid or not a string.
- Use PSJ.ErrCode to check errors if the result is empty.
Limitations
- $$JSON must be valid JSON.
- $$PATH must point to a string value, or an empty string is returned.
See also: