12.8.1 How it works
parseJson(text) returns a Result: Success with a JsonValue, or Error with a JsonError saying what failed and where. On a JsonValue you can ask:
| Operation | Returns |
|---|---|
v.kind() | what kind of value it is: object, array, text, number, boolean or null |
v.field(key) | Something(value) or Nothing |
v.element(i) | Something(value) or Nothing, with indices from zero |
v.keys(), v.length() | the keys in their original order; how many elements |
asInteger, asReal, asText, asBoolean | Something if the value is of that type |
parseJson produces. field and element go down the tree.An object with three fields: nombre with "Ana", edad with 15 and notas with an array of 7 and 9. field("edad") goes down to 15.
ProgramReading a record card
Algorithm Ficha
Switch parseJson('{"nombre": "Ana", "edad": 15, "notas": [7, 9]}') Do
Success(ficha):
Write ficha.keys(), " ", ficha.length();
Switch ficha.field("edad") Do
Some(edad): Write "edad: ", jsonText(edad);
None: Write "sin edad";
EndSwitch
Write jsonText(ficha);
Failure(problema):
Write problema.code;
EndSwitch
EndAlgorithmOutput
["nombre", "edad", "notas"] 3
edad: 15
{"nombre":"Ana","edad":15,"notas":[7,9]}
The program finishes normally.
jsonText writes compact JSON, keeps the order of keys and the original text of numbers. Parsing what it writes gives back the same value.
Parsing is strict: no comments, no trailing commas, no repeated keys. The error gives the line and column where it was detected:
ProgramOne comma too many
Algorithm Roto
Switch parseJson('{"edad": 15,}') Do
Success(ficha): Write jsonText(ficha);
Failure(problema):
Define codigo As JsonErrorCode <- problema.code;
Write codigo, " en ", problema.jsonLine, ":", problema.jsonColumn;
EndSwitch
EndAlgorithmOutput
InvalidSyntax en 1:13
The program finishes normally.
The values of JsonKind and JsonErrorCode are these:
JsonKind | JsonErrorCode |
|---|---|
JsonKind.Object, JsonKind.Array | JsonErrorCode.InvalidSyntax |
JsonKind.JsonStringKind, JsonKind.JsonNumber | JsonErrorCode.UnexpectedEnd, JsonErrorCode.TrailingContent |
JsonKind.JsonBoolean, JsonKind.Null | JsonErrorCode.InvalidEscape, JsonErrorCode.DuplicateKey, JsonErrorCode.DepthExceeded |
In short
parseJsonreturns a value or an error with a position.field,elementandas…returnOptional.jsonTextwrites compact JSON that can be read back.