Bundle JSON parsing and building library. JsonParser reads JSON strings into a JsonElement tree; JsonBuilder constructs JSON documents using a stack-based API. Compile with -lib json.
JsonParser
Support for JSON parsing
Example
doc := Web.HTTP.HttpsClient->QuickGet(Web.HTTP.Url->New("https://dummyjson.com/carts"));
if(doc <> Nil) {
parser := Data.JSON.JsonParser->New(String->New(doc));
if(parser->Parse()) {
carts := parser->GetRoot()->Get("carts");
if(carts->Size() > 0) {
cart := carts->Get(Int->Random(carts->Size()));
cart_id := cart->Get("id")->GetInt();
"cart id={$cart_id}\n---"->PrintLine();
products := cart->Get("products");
each(product := products) {
product_id := product->Get("id")->GetInt();
product_title := product->Get("title")->GetString();
"\tid={$product_id}, title: '{$product_title}'"->PrintLine();
};
};
};
};Operations
GetError #
Get the current parsing error
method : public : GetError() ~ StringReturn
| Type | Description |
|---|---|
| String | parsing error, Nil if none |
Example
parser := Data.JSON.JsonParser->New("{bad json}");
if(<>parser->Parse()) {
parser->GetError()->PrintLine();
};GetRoot #
Get document root
method : public : GetRoot() ~ JsonElementReturn
| Type | Description |
|---|---|
| JsonElement | root Json element |
Example
parser := Data.JSON.JsonParser->New("{\"x\":1}");
parser->Parse();
root := parser->GetRoot();
root->Get("x")->GetInt()->PrintLine(); # 1New # constructor
Constructor
New(stream_in:String)Parameters
| Name | Type | Description |
|---|---|---|
| stream_in | String | JSON string to process |
New # constructor
Constructor
New(stream_in:Char[])Parameters
| Name | Type | Description |
|---|---|---|
| stream_in | Char | JSON character stream |
New # constructor
Constructor
New(stream_in:Byte[])Parameters
| Name | Type | Description |
|---|---|---|
| stream_in | Byte | JSON byte stream |
Parse #
Parses a Json string
method : public : Parse() ~ BoolReturn
| Type | Description |
|---|---|
| Bool | true is successful, false otherwise |
Example
parser := Data.JSON.JsonParser->New("{\"name\":\"Alice\",\"age\":30}");
if(parser->Parse()) {
root := parser->GetRoot();
root->Get("name")->GetString()->PrintLine();
} else {
parser->GetError()->PrintLine();
};TextToElement # function
Parses JSON text
function : TextToElement(text:String) ~ JsonElementParameters
| Name | Type | Description |
|---|---|---|
| text | String | JSON text |
Return
| Type | Description |
|---|---|
| JsonElement | root document element |
Example
elem := Data.JSON.JsonParser->TextToElement("{\"k\":\"v\"}");
elem->Get("k")->GetString()->PrintLine(); # v