BASIC8
Not enough ratings
Using JSON
By Tony Wang
Difficulty: senior
Category: programming
   
Award
Favorite
Favorited
Unfavorite
What is JSON
According to the definition[en.wikipedia.org] from wikipedia, JSON (/ˈdʒeɪsən/ JAY-sən) is the acronym form of "JavaScript Object Notation", it is an open-standard data format that uses human-readable text to transmit data objects consisting of attribute–value pairs and array data types (or any other serializable value). It is a very common data format used for serialization and communication in computer technologies, beyond a subset structure in JavaScript only.

Each data type of JSON has its own corresponding types in BASIC8. See following table for conversions from JSON values to BASIC8 ones, vice versa:


Why use JSON
JSON is friendly to human, it is text-based, and easier than other formats, for example XML, to read and write; JSON is friendly to machine, it is expressive enough to represent variant types of data structures; also JSON is widely used in BASIC8 as:

  • Configuration file
  • Assets, including palette, sprite, tiles, map, etc.
  • Persistence file
  • One of the network message formats
  • Etc.
How to use JSON
Similar to how other library structures are created:

JSON(): creates a JSON object.

A JSON structure is just a set of denotation, without occupying native resources. So just set a variable to NIL when its JSON value is no longer used.

There are a pair of functions transmit JSON in text to JSON in BASIC8, vice versa:

Json.PARSE(txt): parses from a JSON string.
Json.SERIALIZE(): serializes to a JSON string.

Also another pair of functions convert JSON object to list, dictionary, etc. vice versa:

Json.GET(): gets BASIC8 objects and values from a JSON object.
Json.SET(v): sets BASIC8 objects and values to a JSON object.

See the table at the beginning of this guide for details. There's no such boolean type in BASIC8, so we need a helper structure to explicitly tell BASIC8 it should be a JSON boolean, rather than being number:

JSON_BOOL(b): creates a JSON bool with a BASIC8 integer. Returns JSON bool.
UNPACK(b): unpacks a BASIC8 integer from a JSON bool. Returns `TRUE` or `FALSE`.

Snippets:

j = json() c = dict ( "nil", nil, "true", json_bool(true), "false", json_bool(false), "number", 123, "string", "some string", "array", list(1, 4.2, "test"), "object", dict ( "key0", "val0", "key1", "val1", "键", "值" ) ) j.set(c) t = j.serialize() f = file() f.open("output.json", true) f.write(t) f.close() j.parse(t) assert(type(clone(j)) = "JSON") c = j.get() t = c("true") f = c("false") assert(t) assert(not f) assert(unpack(t)) assert(not unpack(f))
1 Comments
andi 20 Aug, 2022 @ 4:16am 
Helpful Guide (would bei nice to find something similar for bitty engine too :steamthumbsup:).
Btw. I like your use of the B8 icon for the guides - do that for be also :)
It is recogniceable and fits perfectly in my opinion.