Working with JSON
Lesson 3: Generating JSON
- The next step after parsing JSON is to generate JSON. Another sample, GenerateExample.src, will be used during this lesson.
- The JSON objects will be dynamically created, and then Stringify will be called at the end to get the string.
- First the JSON object, hoJson, is created using Get Create. Next the InitializeJsonType function is called, which initializes a JSON object as a certain type. When first created the object is not initialized, so it is not yet defined as an object, string, array, etc. From InitializeJsonType it is passed to type as a constant. In this sample jsonTypeObject is used to define it as an object.
- Following, a member value is applied to it with the name, “name,” and it will be a string with a value of “John.” The value is passed a parameter.
- Another JSON object is then created, the hoDetail object. Two member values are applied: “age” as an integer with a value of 31, and “male” which a Boolean set to True. This object is then set as a member of the outermost object, hoJson. The name “details” is passed as hoDetail as the JSON object that is going to be the member of the outermost object.
- hoDetail is then destroyed because it is no longer needed, but it does not destroy the JSON structure that was created in the background. It only destroys the handle to the object.
- peWhiteSpace is set (more to follow).
- Get Stringify is used to get the JSON string to generate the JSON for the objects that have been created.
- Showln sJson shows the string containing the JSON. It contains the name and details (age:31 and male:true). That JSON is put in an output window, and then the last object, hoJson, is destroyed.
Running the sample results in an output window displaying the proper JSON.
Generating JSON – peWhiteSpace
- peWhiteSpace determines the format of the JSON being generated.
- The standard value is jpWhitespace_Plain, which does not include any white space because machines do not need white space to recognize JSON.
- There are two other forms of peWhiteSpace.
- jpWhitespace_Spaced, which adds spaces between the values to make it more readable.
- upWhitespace_Pretty, which adds line views and indents the JSON. This is ideal when debugging or need to manually assess at a later time.