Why enhance JSON handling?
Reading and writing JSON in PowerBuilder is simple using PowerBuilder’s RESTClient object; however, the JSON needs to be in a two-dimensional format. But there are times when the JSON you are working with has multiple nested levels, especially if working with data from an external interface not under your control.
The PowerBuilder objects JSONParser and JSONGenerator can be used to parse or generate such JSON with multiple nested levels. However, a key caveat is that the JSONParser and JSONGenerator require the JSON data to be accessed through “handles”. For example, the getItemObject() returns a handle rather than the full JSON object. Compared to an object-based approach, this handle-based approach requires more coding by the developer.
Another thing to keep in mind is that the JSONParser and JSONGenerator cannot directly modify the JSON data. If you need to do so, you must first parse the JSON file (with the JSONParser), make the desired changes, and regenerate the JSON again (with the JSONGenerator) - or even merge a part of a JSON file into another one. For such requirements, transforming the data from the JSONParser to the JSONGenerator item by item can be tedious.
Fortunately, I have a solution for that. I've created a nonvisual user object called u_json, which can parse, generate and manipulate JSON in an object oriented way.
How it works
u_json works with its own JSON structure. When a file is parsed, it will be completely parsed with JSONParser and then would be available in the object oriented way. When a JSON string is generated, a JSONGenerator object will be created from the object structure.
Each array, object or value is considered a node, each node is represented by an u_json object. Array and object nodes contain an array of u_json objects. With this setup, the JSON information can be easily accessed and manipulated using the dot notation (see examples in the GitHub wiki).
Get it, it's open source
I've published the project on GitHub as open source under the MIT license.
By now, the project isn't thoroughly tested, so there might be some bugs left. But it's working in general. If you find an error or have some ideas how to optimize it, you're very welcome to create an issue or pull request on GitHub. More Information as well as a full function reference can also be found on the GitHub Wiki.
Comments (5)