The following works:
let jsonObj: JSON.Obj = <JSON.Obj>(JSON.parse('{"hello": "world", "value": 24}'));
but if jsonString has an invalid json format, it breaks my subgraph.
Using:
"@graphprotocol/graph-cli": "0.35.0",
"@graphprotocol/graph-ts": "0.29.0",
"assemblyscript-json": "1.1.0"
Since assemblyscript doesn't have support for error handling (try/catch) is there a way to handle an invalid json string with assemblyscript-json ?
Exception handling (and error handling in general) is currently hard to do in AssemblyScript, because the developers are waiting for the WebAssembly exception proposal to go through.
The assemblyscript-json
package is recommended by the documentation, but it seems, at least to me from afar, to be unmaintained actively. Maybe the json-as
package would prove to be useful for you. Still no exception handling, but it does not fail on invalid jsons, it merely returns an object with all nulls and zeros, so you can check it more easily.
import { JSON } from "json-as";
export function test(): Player {
// @ts-ignore
const data: Player = {
firstName: "Emmet",
lastName: "West",
lastActive: [8, 27, 2022],
age: 23,
pos: {
x: -3.4,
y: 1.2
},
isVerified: true
}
return JSON.parse<Player>("[1, 2, 3]"); // invalid json
}
This, for me, returns:
{
firstName: null,
lastName: null,
lastActive: null,
age: 0,
pos: null,
isVerified: false
}
In order to install the package, be sure to call:
npm install --save json-as
because that is the name on the npm, as opposed to the name on github. You can check the package documentation on github, to ensure that this is correct.