Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix readme examples #306

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 13 additions & 7 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ Special thanks to https://github.com/MaxGraey/bignum.wasm for basic unit testing
import { JSON } from "assemblyscript-json";

// Parse an object using the JSON object
let jsonObj: JSON.Obj = <JSON.Obj>(JSON.parse('{"hello": "world", "value": 24}'));
let jsonObj: JSON.Obj = <JSON.Obj>(JSON.parse('{"hello": "world", "age": 24, "temperature": 36.8}'));

// We can then use the .getX functions to read from the object if you know it's type
// This will return the appropriate JSON.X value if the key exists, or null if the key does not exist
Expand All @@ -30,10 +30,16 @@ if (worldOrNull != null) {
let world: string = worldOrNull.valueOf();
}

let numOrNull: JSON.Num | null = jsonObj.getNum("value");
if (numOrNull != null) {
// use .valueOf() to turn the high level JSON.Num type into a f64
let value: f64 = numOrNull.valueOf();
let intOrNull: JSON.Integer | null = jsonObj.getInteger("age");
if (intOrNull != null) {
// use .valueOf() to turn the high level JSON.Integer type into a i64
let age: i64 = intOrNull.valueOf();
}

let floatOrNull: JSON.Float | null = jsonObj.getFloat("temperature");
if (floatOrNull != null) {
// use .valueOf() to turn the high level JSON.Float type into a f64
let temperature: f64 = floatOrNull.valueOf();
}

// If you don't know the value type, get the parent JSON.Value
Expand Down Expand Up @@ -71,9 +77,9 @@ encoder.popObject();
let json: Uint8Array = encoder.serialize();

// Or get serialized data as string
let jsonString: string = encoder.stringify();
let jsonString: string = encoder.toString();

assert(jsonString, '"obj": {"int": 10, "str": ""}'); // True!
assert(jsonString == '\"obj\":{\"int\":10,\"str\":\"\"}'); // True!
```

### Custom JSON Deserializers
Expand Down