JSON
Reading, making and writing JSON data (RFC 7159), and moving it into and out of the program's own arrays, lists, maps and structures.
- A #JSON holds one JSON value: made empty with
CreateJSON, or read from text withParseJSON,CatchJSONorLoadJSON. Like files, it is a number (0 to 4095) or#PB_Any. - A value is an address (
JSONValue(#JSON)gives the top one). Values inside arrays and objects belong to the #JSON, and go when it is freed or when the value holding them changes. - A value's type is one of
#PB_JSON_Null,#PB_JSON_String,#PB_JSON_Number,#PB_JSON_Boolean,#PB_JSON_Array,#PB_JSON_Object(0 to 5). TheSetJSON...functions change a value's type; theGetJSON...functions read it. - A number is kept as an integer (
42, written without a point or exponent) or as a double.GetJSONIntegercuts a double to an integer (1.9gives1), and a boolean reads as0or1. Reading the wrong type gives0or"". - An object's members match their keys with case, unless the #JSON was made or read with
#PB_JSON_NoCase.
x is compatible with PureBasic 6.50, with the same constant values, text layout, number formats and error messages. x keeps an object's members in the order they were added.
Making and freeing
CreateJSON ✅
Result = CreateJSON(#JSON [, Flags])
New JSON data, whose value is null. Flags: #PB_JSON_NoCase, for member keys in any case. Returns nonzero (with #PB_Any: the new #JSON).
FreeJSON ✅
FreeJSON(#JSON)
Frees the data and all its values. FreeJSON(#PB_All) frees all of them.
IsJSON ✅
Result = IsJSON(#JSON)
Nonzero if #JSON is JSON data. Any value may be given.
JSONValue ✅
Result = JSONValue(#JSON)
The data's value.
OpenConsole()
If CreateJSON(0)
person = SetJSONObject(JSONValue(0))
SetJSONString(AddJSONMember(person, "FirstName"), "John")
SetJSONString(AddJSONMember(person, "LastName"), "Smith")
SetJSONInteger(AddJSONMember(person, "Age"), 42)
books = SetJSONArray(AddJSONMember(person, "Books"))
SetJSONString(AddJSONElement(books), "Investing For Dummies")
SetJSONNull(AddJSONElement(books))
PrintN(ComposeJSON(0))
FreeJSON(0)
EndIf
Output:
{"FirstName":"John","LastName":"Smith","Age":42,"Books":["Investing For Dummies",null]}
Reading JSON text
ParseJSON ✅
Result = ParseJSON(#JSON, Input$ [, Flags])
Reads JSON text into new JSON data. Flags: #PB_JSON_NoCase. Returns nonzero (with #PB_Any: the new #JSON), or zero if the text isn't JSON. If it fails, data already of that number is kept.
As in PureBasic:
- Any value can be the top one (
42,"text"), with spaces, tabs and line breaks around it. - Leading zeros are allowed (
01is1). - An integer with too many digits wraps around.
- Control characters (a tab) may be in strings.
- A member given twice keeps the last value.
- Arrays and objects may be nested at most 1000 deep.
CatchJSON ✅
Result = CatchJSON(#JSON, *Buffer, Size [, Flags])
Reads JSON text of Size bytes in UTF-8 from memory. A UTF-8 byte order mark at the start is skipped.
LoadJSON ✅
Result = LoadJSON(#JSON, Filename$ [, Flags])
Reads a JSON file (UTF-8; a byte order mark is skipped).
JSONErrorMessage ✅, JSONErrorLine ✅, JSONErrorPosition ✅
Message$ = JSONErrorMessage()
Line = JSONErrorLine()
Position = JSONErrorPosition()
Why the last parse failed, and where: the line (from 1) and the character in that line (from 1). At the end of the input, the position is that of the last character. After a parse that worked, the message is "" and the line and position are -1. The messages (as PureBasic's):
| Message |
|---|
Unexpected character |
Unexpected end of input |
Expected a ':' character |
A member name (string) is expected |
Invalid escape sequence |
JSON nesting is too deep |
OpenConsole()
If ParseJSON(0, "[1, 2, 3 4]") = 0
PrintN(JSONErrorMessage() + " at line " + Str(JSONErrorLine()) + ", character " + Str(JSONErrorPosition()))
EndIf
If ParseJSON(0, "{" + Chr(10) + " " + Chr(34) + "a" + Chr(34) + " 1}") = 0
PrintN(JSONErrorMessage() + " at line " + Str(JSONErrorLine()) + ", character " + Str(JSONErrorPosition()))
EndIf
If ParseJSON(0, "[true, fals")= 0
PrintN(JSONErrorMessage())
EndIf
Output:
Unexpected character at line 1, character 10
Expected a ':' character at line 2, character 7
Unexpected end of input
Writing JSON text
ComposeJSON ✅
Text$ = ComposeJSON(#JSON [, Flags])
The data as JSON text. With #PB_JSON_PrettyPrint, it's laid out on lines as PureBasic lays it out:
- array elements 2 spaces in;
- object members 2 spaces in, with their keys padded to the longest key;
- each member's value 4 spaces in from its object;
- Windows line breaks on Windows.
How things are written:
- Strings:
"and\get a backslash; control characters are written as\n,\tand the like (\u0001); everything else as it is,/included. - Doubles: in the fewest digits that read back as the same number (
0.1,1e+300,1.5e-10). - NaN and infinity: written as
null.
OpenConsole()
ParseJSON(0, "{" + Chr(34) + "name" + Chr(34) + ": " + Chr(34) + "Ann" + Chr(34) + ", " + Chr(34) + "scores" + Chr(34) + ": [1.5, 0.1, 2e3], " + Chr(34) + "ok" + Chr(34) + ": true}")
PrintN(ComposeJSON(0))
PrintN(ComposeJSON(0, #PB_JSON_PrettyPrint))
Output:
{"name":"Ann","scores":[1.5,0.1,2000],"ok":true}
{
"name" : "Ann",
"scores": [
1.5,
0.1,
2000
],
"ok" : true
}
SaveJSON ✅
Result = SaveJSON(#JSON, Filename$ [, Flags])
Writes the data to a file in UTF-8, without a byte order mark. Flags: #PB_JSON_PrettyPrint. An existing file is replaced only once the new one has been written. Returns nonzero if it worked.
ExportJSON ✅, ExportJSONSize ✅
Result = ExportJSON(#JSON, *Buffer, Size [, Flags])
Result = ExportJSONSize(#JSON [, Flags])
The text, in UTF-8, into memory. ExportJSON returns the bytes written, or 0 if Size is too small (the memory is filled as far as it goes). ExportJSONSize returns the bytes needed.
OpenConsole()
CreateJSON(0)
SetJSONString(JSONValue(0), "café")
*m = AllocateMemory(ExportJSONSize(0))
PrintN(Str(ExportJSON(0, *m, MemorySize(*m))) + " bytes")
CatchJSON(1, *m, MemorySize(*m))
PrintN(GetJSONString(JSONValue(1)))
Output:
7 bytes
café
Values
JSONType ✅
Result = JSONType(JSONValue)
The value's type: #PB_JSON_Null, #PB_JSON_String, #PB_JSON_Number, #PB_JSON_Boolean, #PB_JSON_Array or #PB_JSON_Object.
SetJSONNull ✅, SetJSONBoolean ✅, SetJSONInteger ✅, SetJSONQuad ✅, SetJSONFloat ✅, SetJSONDouble ✅, SetJSONString ✅
SetJSONNull(JSONValue)
SetJSONBoolean(JSONValue, Value)
SetJSONInteger(JSONValue, Value)
SetJSONQuad(JSONValue, Value.q)
SetJSONFloat(JSONValue, Value.f)
SetJSONDouble(JSONValue, Value.d)
SetJSONString(JSONValue, Text$)
The value becomes that type, with that value (whatever it held before goes). A boolean is true for any nonzero value.
SetJSONArray ✅, SetJSONObject ✅
Result = SetJSONArray(JSONValue)
Result = SetJSONObject(JSONValue)
The value becomes an empty array or object. Returns the value.
GetJSONBoolean ✅, GetJSONInteger ✅, GetJSONQuad ✅, GetJSONFloat ✅, GetJSONDouble ✅, GetJSONString ✅
Result = GetJSONBoolean(JSONValue)
Result = GetJSONInteger(JSONValue)
Result.q = GetJSONQuad(JSONValue)
Result.f = GetJSONFloat(JSONValue)
Result.d = GetJSONDouble(JSONValue)
Text$ = GetJSONString(JSONValue)
The value, read as that type.
OpenConsole()
Procedure.s Describe(v)
Select JSONType(v)
Case #PB_JSON_Null : ProcedureReturn "null"
Case #PB_JSON_String : ProcedureReturn "string " + GetJSONString(v)
Case #PB_JSON_Number : ProcedureReturn "number " + StrD(GetJSONDouble(v)) + " (integer " + Str(GetJSONInteger(v)) + ")"
Case #PB_JSON_Boolean : ProcedureReturn "boolean " + Str(GetJSONBoolean(v))
Case #PB_JSON_Array : ProcedureReturn "array of " + Str(JSONArraySize(v))
Case #PB_JSON_Object : ProcedureReturn "object of " + Str(JSONObjectSize(v))
EndSelect
EndProcedure
ParseJSON(0, "[1, -2.75, true, null, " + Chr(34) + "hi" + Chr(34) + ", [], {}]")
For i = 0 To JSONArraySize(JSONValue(0)) - 1
PrintN(Describe(GetJSONElement(JSONValue(0), i)))
Next
Output:
number 1 (integer 1)
number -2.75 (integer -2)
boolean 1
null
string hi
array of 0
object of 0
Arrays
JSONArraySize ✅
Result = JSONArraySize(JSONValue)
How many elements.
GetJSONElement ✅
Result = GetJSONElement(JSONValue, Index)
The element at Index (from 0), or 0 if there is none.
AddJSONElement ✅
Result = AddJSONElement(JSONValue [, Index])
A new element (null): at the end, or put at Index (below 0: at the start; past the end: at the end). Returns it.
RemoveJSONElement ✅, ResizeJSONElements ✅, ClearJSONElements ✅
RemoveJSONElement(JSONValue, Index)
ResizeJSONElements(JSONValue, Size)
ClearJSONElements(JSONValue)
Remove one element; make the array Size elements long (new ones are null); remove them all.
OpenConsole()
ParseJSON(0, "[1, 2, 3, 4, 5]")
a = JSONValue(0)
SetJSONString(AddJSONElement(a, 1), "two")
SetJSONString(AddJSONElement(a, -1), "first")
PrintN(ComposeJSON(0))
RemoveJSONElement(a, 0)
ResizeJSONElements(a, 3)
PrintN(ComposeJSON(0))
ResizeJSONElements(a, 5)
PrintN(ComposeJSON(0) + " has " + Str(JSONArraySize(a)))
Output:
["first",1,"two",2,3,4,5]
[1,"two",2]
[1,"two",2,null,null] has 5
Objects
JSONObjectSize ✅
Result = JSONObjectSize(JSONValue)
How many members.
AddJSONMember ✅
Result = AddJSONMember(JSONValue, Key$)
A member for Key$ (null). If there is one already, it is emptied and keeps its place (and its key as written). Returns its value.
GetJSONMember ✅
Result = GetJSONMember(JSONValue, Key$)
The member's value, or 0 if there is none.
RemoveJSONMember ✅, ClearJSONMembers ✅
RemoveJSONMember(JSONValue, Key$)
ClearJSONMembers(JSONValue)
Remove one member; remove them all.
ExamineJSONMembers ✅, NextJSONMember ✅, JSONMemberKey ✅, JSONMemberValue ✅
Result = ExamineJSONMembers(JSONValue)
Result = NextJSONMember(JSONValue)
Key$ = JSONMemberKey(JSONValue)
Result = JSONMemberValue(JSONValue)
Go through an object's members: ExamineJSONMembers starts, NextJSONMember moves to the next (zero when there are no more), then JSONMemberKey and JSONMemberValue give it.
OpenConsole()
ParseJSON(0, "{" + Chr(34) + "Width" + Chr(34) + ": 800, " + Chr(34) + "Height" + Chr(34) + ": 600, " + Chr(34) + "Title" + Chr(34) + ": " + Chr(34) + "Demo" + Chr(34) + "}", #PB_JSON_NoCase)
o = JSONValue(0)
If ExamineJSONMembers(o)
While NextJSONMember(o)
PrintN(JSONMemberKey(o) + " is of type " + Str(JSONType(JSONMemberValue(o))))
Wend
EndIf
PrintN("width: " + Str(GetJSONInteger(GetJSONMember(o, "WIDTH"))))
SetJSONInteger(AddJSONMember(o, "height"), 768)
RemoveJSONMember(o, "title")
PrintN(ComposeJSON(0))
Output:
Width is of type 2
Height is of type 2
Title is of type 1
width: 800
{"Width":800,"Height":768}
The program's own data
These turn arrays, lists, maps and structures into JSON and back, all the way down: structures inside structures, static arrays (field.l[3]), and Array, List and Map fields.
- Arrays and lists become JSON arrays. A two-dimensional array becomes an array of arrays.
- Maps and structures become objects. A structure's members are its fields, keyed by their names as written, without
$and*. - Pointers become numbers. Fixed-length strings (
.s{n}) become strings, and are cut to fit when extracted.
Extracting, a value of the wrong type is left empty (0 or ""); a boolean reads as 0 or 1 into a number.
InsertJSONArray ✅, InsertJSONList ✅, InsertJSONMap ✅
InsertJSONArray(JSONValue, Array())
InsertJSONList(JSONValue, List())
InsertJSONMap(JSONValue, Map())
The value becomes an array (an object, for a map) holding the elements.
InsertJSONStructure ✅
InsertJSONStructure(JSONValue, *Buffer, Structure)
The value becomes an object holding the fields of the structure at *Buffer.
ExtractJSONArray ✅, ExtractJSONList ✅, ExtractJSONMap ✅
ExtractJSONArray(JSONValue, Array())
ExtractJSONList(JSONValue, List())
ExtractJSONMap(JSONValue, Map())
The elements of a JSON array (an object, for a map) replace what the collection held. The array is made the JSON array's size; a two-dimensional one is made the outer array's size by the longest inner array.
ExtractJSONStructure ✅
ExtractJSONStructure(JSONValue, *Buffer, Structure [, Flags])
The members of a JSON object go into the structure at *Buffer, field by field, matched by name (with case, unless the data is #PB_JSON_NoCase). The structure is emptied first, unless Flags is #PB_JSON_NoClear: then fields without a member keep their value.
OpenConsole()
Structure Location
x.l
y.l
EndStructure
Structure Trip
Name$
Days.w
List Stops.Location()
Map Costs.d()
EndStructure
Define t.Trip
t\Name$ = "Coast" : t\Days = 3
AddElement(t\Stops()) : t\Stops()\x = 10 : t\Stops()\y = 20
AddElement(t\Stops()) : t\Stops()\x = -5 : t\Stops()\y = 7
t\Costs("hotel") = 240.5 : t\Costs("food") = 80
CreateJSON(0)
InsertJSONStructure(JSONValue(0), @t, Trip)
text$ = ComposeJSON(0)
PrintN(text$)
ParseJSON(1, text$)
Define back.Trip
ExtractJSONStructure(JSONValue(1), @back, Trip)
PrintN(back\Name$ + ", " + Str(back\Days) + " days, " + Str(ListSize(back\Stops())) + " stops, hotel " + StrD(back\Costs("hotel")))
Dim grid(1, 2)
grid(0, 0) = 1 : grid(1, 2) = 6
InsertJSONArray(JSONValue(0), grid())
PrintN(ComposeJSON(0))
ParseJSON(2, "[[1, 2], [3, 4, 5]]")
Dim g(0, 0)
ExtractJSONArray(JSONValue(2), g())
PrintN(Str(ArraySize(g(), 1)) + " by " + Str(ArraySize(g(), 2)) + ", g(1, 2) = " + Str(g(1, 2)))
Output:
{"Name":"Coast","Days":3,"Stops":[{"x":10,"y":20},{"x":-5,"y":7}],"Costs":{"hotel":240.5,"food":80}}
Coast, 3 days, 2 stops, hotel 240.5
[[1,0,0],[0,0,6]]
1 by 2, g(1, 2) = 5