Try OpenEdge Now
skip to main content
Working with JSON
Reading and Serializing JSON to/from ProDataSets and Temp-tables : Writing JSON from a temp-table, temp-table buffer, or a ProDataSet : Writing JSON from a ProDataSet
 

Writing JSON from a ProDataSet

The following code example defines a static ProDataSet object, attaches its data sources, fills the ProDataSet object, and writes the ProDataSet object to a JSON string:
/* write-json-pds1.p */
{pi-json-parameterVarDefs.i} /* parameter variable definitions */
{pi-write-json-pds1.i}       /* dsOrderLog definition - no nesting */

DEFINE VARIABLE hdsOrderLog AS HANDLE  NO-UNDO.
DEFINE VARIABLE lRetOK      AS LOGICAL NO-UNDO.

hdsOrderLog = DATASET dsOrderLog:HANDLE.

DATA-SOURCE dsCustomer:FILL-WHERE-STRING = "WHERE Customer.CustNum = 2 ".
DATASET dsOrderLog:FILL().

ASSIGN
  cTargetType = "file"
  cFile       = "dsOrderLog.json"
  lFormatted  = TRUE
  cEncoding   = ?.

lRetOK = hdsOrderLog:WRITE-JSON(cTargetType, cFile, lFormatted).
The following is an excerpt of the JSON produced by this procedure:
{"dsOrderLog": {
  "ttCustomer": [
    {
      "CustNum": 2,
      ...
    }
  ],
  "ttOrder": [
    {
      "Ordernum": 94,
      ...
    },
    ...
    {
      "Ordernum": 6070,
      ...
    }
  ],
  "ttInvoice": [
    {
      "Invoicenum": 94,
      ...
    },
    {
      "Invoicenum": 124,
      ...
    }
  ]
}}
Because the ProDataSet definition did not include the NESTED option for the data-relations, the records from each temp-table are presented after each other. If you do not nest child tables, the JSON does not contain the data relation information. The serialization process also loses any information about key columns.
If you run write-json-pds2.p which uses a ProDataSet with nested child tables, the resulting JSON looks like this:
{"dsOrderLog": {
  "ttCustomer": [
    {
      "CustNum": 2,
      ...
      "EmailAddress": "",
      "ttOrder": [
        {
          "Ordernum": 94,
          ...
          "Carrier": "Standard Mail",
          "ttInvoice": [
            {
              "Invoicenum": 94,
              ...
            }
          ]
        },
        {
          "Ordernum": 125,
          ...
          "Carrier": "FlyByNight Courier",
          "ttInvoice": [
            {
              "Invoicenum": 124,
              ...
            }
          ]
        },
        ...      ]
    }
  ]
}}