PSJ. - JSON Operations

<< Click to Display Table of Contents >>

Navigation:  3. Script Language > JSON - Parser > Parser-Operations > !Document Operations >

PSJ. - JSON Operations

PSJ.NodeToStr

Previous Top Next


SPR Script Language

 

PSJ.NodeToStr

Serializes a specific JSON node and its entire subtree into a JSON-formatted string.

 

Intention

 

Use the PSJ.NodeToStr command when you need to extract a part of a larger JSON document and represent it as its own valid JSON string. Unlike PSJ.ToString, which serializes an entire document from its handle, this command starts from a specific Node ID. This is perfect for isolating an object or an array within your data structure for logging, debugging, or sending to another process or API call.

 

You can also choose to format the output string for readability ("pretty-print") or keep it compact for efficiency.

 

Syntax

 

PSJ.NodeToStr|$$NID[|$$PRT|$$IND|$$RET]

 

Parameter Explanation

 

P1 - $$NID - (Variable, numeric, Required)

The Node ID of the element where serialization should begin. This node and all its children will be included in the output string.

 

P2 - $$PRT - (Variable, numeric, Optional)

The pretty-print flag. Set to 1 to format the output with indentation and newlines for readability. If 0 or omitted, the output will be a compact, single-line string.

 

P3 - $$IND - (Variable, numeric, Optional)

The number of spaces to use for each level of indentation when pretty-printing is enabled. If omitted, defaults to 2.

 

P4 - $$RET - (Variable, String, Optional)

The variable to store the resulting JSON string. If omitted, the string is returned on the top-of-stack (TOS).

 

Examples

 

'***********************************

' PSJ.NodeToStr - Sample 1: Extract and serialize a sub-object

'***********************************

VAR.$$JSN={"user":{"name":"John","details":{"age":30,"city":"New York"}}}

PSJ.Parse|$$JSN|$$H_1

JIZ.$$H_1|Lab_failed

 

' Get the Node ID of the "details" object

PSJ.GetByPath|$$H_1|user.details|0|$$NID

JIZ.$$NID|Lab_failed

 

' Serialize just the "details" node into $$VAL

PSJ.NodeToStr|$$NID|||$$VAL

 

' $$VAL will contain: {"age":30,"city":"New York"}

MBX.Serialized Node:|$$VAL

 

PSJ.Free|$$H_1

END.

 

'***********************************

' PSJ.NodeToStr - Sample 2: Pretty-print an array

'***********************************

VAR.$$JSN={"items":["Apple","Banana","Cherry"]}

PSJ.Parse|$$JSN|$$H_1

PSJ.GetByPath|$$H_1|items|0|$$NID

 

' Serialize the "items" array with pretty-printing and 4-space indents

PSJ.NodeToStr|$$NID|1|4|$$VAL

 

MBX.Pretty-Printed Array:|$$VAL

PSJ.Free|$$H_1

END.

 

Remarks

 

- The output string is always encoded in UTF-8.

- If the specified Node ID is invalid or has been freed, the command will return an empty string and set an error. Use PSJ.ErrCode to check for failures.

 

See also:

 

PSJ.ToString

PSJ.GetByPath

PSJ.SaveFile