Skip to content

SpecificationXII · Library

12.8

JSON

parseJson turns a JSON text into a value you can walk through, and jsonText goes the other way.

Markdown version

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:

OperationReturns
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, asBooleanSomething if the value is of that type
Figure 12.8-1.The JSON text and the tree of values 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
EndAlgorithm

Output

["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
EndAlgorithm

Output

InvalidSyntax en 1:13

The program finishes normally.

The values of JsonKind and JsonErrorCode are these:

JsonKindJsonErrorCode
JsonKind.Object, JsonKind.ArrayJsonErrorCode.InvalidSyntax
JsonKind.JsonStringKind, JsonKind.JsonNumberJsonErrorCode.UnexpectedEnd, JsonErrorCode.TrailingContent
JsonKind.JsonBoolean, JsonKind.NullJsonErrorCode.InvalidEscape, JsonErrorCode.DuplicateKey, JsonErrorCode.DepthExceeded

In short

  • parseJson returns a value or an error with a position.
  • field, element and as… return Optional.
  • jsonText writes compact JSON that can be read back.