Skip to content

Commit c6508f5

Browse files
authored
API Fixes, README cleanup, and generated Reference Documentation (#121)
* Got most of the JSON API cleaned up * Added support for generating docs * Finished deploying docs * Added the docs to the README * Removed the quotes on Str.toString() * One last comment on getX functions * Added a test for toString all the values
1 parent ec60316 commit c6508f5

27 files changed

+4962
-344
lines changed

.gitignore

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
node_modules/
22
build/
3+
temp-docs/
34
tests/build
45
.DS_Store
56

.travis.yml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,3 +5,4 @@ node_js:
55

66
script:
77
- yarn test
8+
- yarn docs

README.md

Lines changed: 102 additions & 73 deletions
Original file line numberDiff line numberDiff line change
@@ -1,28 +1,61 @@
11
# assemblyscript-json
22

3+
![npm version](https://img.shields.io/npm/v/assemblyscript-json) ![npm downloads per month](https://img.shields.io/npm/dm/assemblyscript-json)
4+
35
JSON encoder / decoder for AssemblyScript.
46

57
Special thanks to https://github.com/MaxGraey/bignum.wasm for basic unit testing infra for AssemblyScript.
68

7-
# Limitations
9+
## Installation
10+
11+
`assemblyscript-json` is available as a [npm package](https://www.npmjs.com/package/assemblyscript-json). You can install `assemblyscript-json` in your AssemblyScript project by running:
812

9-
This is developed for use in smart contracts written in AssemblyScript for https://github.com/nearprotocol/nearcore.
10-
This imposes such limitations:
13+
`npm install --save assemblyscript-json`
1114

12-
- Float numbers not supported
13-
- We assume that memory never needs to be deallocated (cause these contracts are short-lived).
15+
## Usage
1416

15-
Note that this mostly just defines the way it's currently implemented. Contributors are welcome to fix limitations.
17+
### Parsing JSON
1618

17-
# Usage
19+
```typescript
20+
import { JSON } from "assemblyscript-json";
1821

19-
## Encoding JSON
22+
// Parse an object using the JSON object
23+
let jsonObj: JSON.Obj = <JSON.Obj>(JSON.parse('{"hello": "world", "value": 24}'));
2024

21-
```ts
22-
// Make sure memory allocator is available
23-
import "allocator/arena";
24-
// Import encoder
25-
import { JSONEncoder } from "path/to/module";
25+
// We can then use the .getX functions to read from the object if you know it's type
26+
// This will return the appropriate JSON.X value if the key exists, or null if the key does not exist
27+
let worldOrNull: JSON.Str | null = jsonObj.getString("hello"); // This will return a JSON.Str or null
28+
if (worldOrNull != null) {
29+
// use .valueOf() to turn the high level JSON.Str type into a string
30+
let world: string = worldOrNull.valueOf();
31+
}
32+
33+
let numOrNull: JSON.Num | null = jsonObj.getNum("value");
34+
if (numOrNull != null) {
35+
// use .valueOf() to turn the high level JSON.Num type into a f64
36+
let value: f64 = numOrNull.valueOf();
37+
}
38+
39+
// If you don't know the value type, get the parent JSON.Value
40+
let valueOrNull: JSON.Value | null = jsonObj.getValue("hello");
41+
if (valueOrNull != null) {
42+
let value: JSON.Value = changetype<JSON.Value>(valueOrNull);
43+
44+
// Next we could figure out what type we are
45+
if(value.isString) {
46+
// value.isString would be true, so we can cast to a string
47+
let stringValue: string = changetype<JSON.Str>(value).toString();
48+
49+
// Do something with string value
50+
}
51+
}
52+
```
53+
54+
### Encoding JSON
55+
56+
57+
```typescript
58+
import { JSONEncoder } from "assemblyscript-json";
2659

2760
// Create encoder
2861
let encoder = new JSONEncoder();
@@ -37,83 +70,79 @@ encoder.popObject();
3770
let json: Uint8Array = encoder.serialize();
3871

3972
// Or get serialized data as string
40-
let jsonString: String = encoder.toString();
73+
let jsonString: string = encoder.toString();
74+
75+
assert(jsonString, '"obj": {"int": 10, "str": ""}'); // True!
4176
```
4277

43-
## Parsing JSON
78+
### Custom JSON Deserializers
4479

45-
```ts
46-
// Make sure memory allocator is available
47-
import "allocator/arena";
48-
// Import decoder
49-
import { JSONDecoder, JSONHandler } from "path/to/module";
80+
```typescript
81+
import { JSONDecoder, JSONHandler } from "assemblyscript-json";
5082

5183
// Events need to be received by custom object extending JSONHandler.
5284
// NOTE: All methods are optional to implement.
5385
class MyJSONEventsHandler extends JSONHandler {
54-
setString(name: string, value: string): void {
55-
// Handle field
56-
}
57-
58-
setBoolean(name: string, value: bool): void {
59-
// Handle field
60-
}
61-
62-
setNull(name: string): void {
63-
// Handle field
64-
}
65-
66-
setInteger(name: string, value: i32): void {
67-
// Handle field
68-
}
69-
70-
pushArray(name: string): bool {
71-
// Handle array start
72-
// true means that nested object needs to be traversed, false otherwise
73-
// Note that returning false means JSONDecoder.startIndex need to be updated by handler
74-
return true;
75-
}
76-
77-
popArray(): void {
78-
// Handle array end
79-
}
80-
81-
pushObject(name: string): bool {
82-
// Handle object start
83-
// true means that nested object needs to be traversed, false otherwise
84-
// Note that returning false means JSONDecoder.startIndex need to be updated by handler
85-
return true;
86-
}
87-
88-
popObject(): void {
89-
// Handle object end
90-
}
86+
setString(name: string, value: string): void {
87+
// Handle field
88+
}
89+
90+
setBoolean(name: string, value: bool): void {
91+
// Handle field
92+
}
93+
94+
setNull(name: string): void {
95+
// Handle field
96+
}
97+
98+
setInteger(name: string, value: i64): void {
99+
// Handle field
100+
}
101+
102+
setFloat(name: string, value: f64): void {
103+
// Handle field
104+
}
105+
106+
pushArray(name: string): bool {
107+
// Handle array start
108+
// true means that nested object needs to be traversed, false otherwise
109+
// Note that returning false means JSONDecoder.startIndex need to be updated by handler
110+
return true;
111+
}
112+
113+
popArray(): void {
114+
// Handle array end
115+
}
116+
117+
pushObject(name: string): bool {
118+
// Handle object start
119+
// true means that nested object needs to be traversed, false otherwise
120+
// Note that returning false means JSONDecoder.startIndex need to be updated by handler
121+
return true;
122+
}
123+
124+
popObject(): void {
125+
// Handle object end
126+
}
91127
}
92128

93129
// Create decoder
94130
let decoder = new JSONDecoder<MyJSONEventsHandler>(new MyJSONEventsHandler());
95131

96-
// Let's assume JSON data is available in this variable
97-
let json: Uint8Array = ...;
132+
// Create a byte buffer of our JSON. NOTE: Deserializers work on UTF8 string buffers.
133+
let jsonString = '{"hello": "world"}';
134+
let jsonBuffer = Uint8Array.wrap(String.UTF8.encode(jsonString));
98135

99136
// Parse JSON
100-
decoder.deserialize(json); // This will send events to MyJSONEventsHandler
101-
137+
decoder.deserialize(jsonBuffer); // This will send events to MyJSONEventsHandler
102138
```
103139

104-
## JSON namespace
140+
Feel free to look through the [tests](https://github.com/nearprotocol/assemblyscript-json/tree/master/assembly/__tests__) for more usage examples.
105141

106-
```ts
107-
import { JSON } from "path/to/module";
142+
## Reference Documentation
108143

109-
// Can use JS parse api
110-
let jsonObj: JSON.Object = JSON.parse(`{"hello": "world"}`);
144+
Reference API Documentation can be found in the [docs directory](./docs).
111145

112-
// Can then use a key to read from the object if you know it's type
113-
let world = jsonObj.getString("hello");
146+
## License
114147

115-
// If you don't know what the type of the value
116-
let unknown = jsonObj.getValue("hello");
117-
118-
unknown.isString; // true;
119-
```
148+
[MIT](./LICENSE)

0 commit comments

Comments
 (0)