Skip to content

Instantly share code, notes, and snippets.

@sergiobuj
Created October 18, 2022 02:18
Show Gist options
  • Save sergiobuj/61f732675b79577ddc4d3cff90b6105f to your computer and use it in GitHub Desktop.
Save sergiobuj/61f732675b79577ddc4d3cff90b6105f to your computer and use it in GitHub Desktop.
Testing "assemblyscript-json" to parse a custom object
import { JSON } from "assemblyscript-json/assembly";
// Parse an object using the JSON object
const payload = `
'{
"hello": "world",
"value": 24,
"pack": {
"123": {
"1": 10
},
"456": {
"2": 20
}
}
}'
`;
type Count = Map<string, number>;
export function fib(): void {
let jsonObj: JSON.Obj = <JSON.Obj>JSON.parse(payload);
// 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
let worldOrNull: JSON.Str | null = jsonObj.getString("hello"); // This will return a JSON.Str or null
if (worldOrNull) {
// use .valueOf() to turn the high level JSON.Str type into a string
let world: string = worldOrNull.valueOf();
console.log(world);
}
let numOrNull: JSON.Num | null = jsonObj.getNum("value");
if (numOrNull) {
// use .valueOf() to turn the high level JSON.Num type into a f64
let value: f64 = numOrNull.valueOf();
console.log(value.toString());
}
// If you don't know the value type, get the parent JSON.Value
let valueOrNull: JSON.Value | null = jsonObj.getValue("hello");
if (valueOrNull) {
let value = <JSON.Value>valueOrNull;
// Next we could figure out what type we are
if (value.isString) {
// value.isString would be true, so we can cast to a string
let innerString = (<JSON.Str>value).valueOf();
let jsonString = (<JSON.Str>value).stringify();
// Do something with string value
}
}
const perPack: Map<string, Count> = new Map<string, Count>();
let pack: JSON.Obj | null = jsonObj.getObj("pack");
if (!pack) return;
let packIds = pack.keys;
for (let index = 0; index < packIds.length; index++) {
const packConfig: JSON.Obj | null = pack.getObj(packIds[index]);
if (!packConfig) continue;
let itemCounts = packConfig.keys;
const discountConfigMap: Count = new Map();
for (let index = 0; index < itemCounts.length; index++) {
const discountConfig: JSON.Obj | null = packConfig.getObj(
itemCounts[index]
);
if (!discountConfig) continue;
let value: JSON.Num | null = discountConfig.getNum(itemCounts[index]);
if (!value) continue;
discountConfigMap.set(itemCounts[index], value.valueOf());
}
perPack.set(packIds[index], discountConfigMap);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment