07. December 2020
Parsing JSON
Especially when testing websites, you are now and then faced with the problem of having to parse JSON (=JavaScript Object Notation) strings.
Often, for this, a JSON library is downloaded and placed into the corresponding plugin directory. After a restart it is then possible to e.g. use the Python JSON library in Jython scripts.
In this blog article, however, the JSON library provided by QF-Test should be described. This library is based on the minimal-json-library and has the advantage that:
- it is already supplied with QF-Test (so not a plugin first must be installed)
- It is available in both Jython and Groovy scripts
The following chapters describe how this library can be used for JSON parsing and JSON generation.
JSON parsing
The general code to parse a JSON string using this library looks like this:
from de.qfs.lib.json import Json jsonStr = """{"a" : 1, "b" : "zzz", "c" : [1,2,3]}""" json = Json.parse(jsonStr)
(Jython Code to parse a Jython String)
import de.qfs.lib.json.Json
def jsonStr = """{"a" : 1, "b" : "zzz", "c" : [1,2,3]}"""
def json = Json.parse(jsonStr)
(Groovy Code to parse a Jython String)
Afterwards, you can easily access the different values defined in the JSON string:
qf.println(json["a"]) # Output: 1 qf.println(json["b"]) # Output: zzz qf.println(json["c"]) # Output: [1,2,3] qf.println(json["c"][0]) # Output: 1 qf.println(json["c"][1]) # Output: 2 qf.println(json["c"][2]) # Output: 3
(Jython Code in order to access the various values / output them on the terminal)
qf.println(json["a"]) // Output: 1 qf.println(json["b"]) // Output: zzz qf.println(json["c"]) // Output: [1,2,3] qf.println(json["c"][0]) // Output: 1 qf.println(json["c"][1]) // Output: 2 qf.println(json["c"][2]) // Output: 3
(Groovy Code in order to access the various values / output them on the terminal)
In Groovy, the following notation is also possible for JSON Maps:
qf.println(json.a) // Output: 1
(Groovy Code in order to access the various values / output them on the terminal)
which makes it possible to "save" further characters in the script. In this context let me also point to Groovy's ?-Notation which is helpful when a certain value can be present in the JSON string but does not have to be present.
Generating JSON
The general code to generate a JSON string using this library looks like this:
from de.qfs.lib.json import JsonBuilder obj = { "a" : [1,2,3,4] } jsonStr = JsonBuilder.toJsonValue(obj) (Jython code to generate a JSON string from an object)
import de.qfs.lib.json.JsonBuilder def obj = [ "a" : [1,2,3,4] ] def jsonStr = JsonBuilder.toJsonValue(obj) (Groovy code to generate a JSON string from an object)