assemblyscript-json icon indicating copy to clipboard operation
assemblyscript-json copied to clipboard

Docs are outdated. How to call `JSON.stringify()`?

Open ryancwalsh opened this issue 3 years ago • 8 comments

I'm looking for a replacement of JSON.stringify() that I can call in my NEAR AssemblyScript contract.

I found this repo.

https://github.com/near/assemblyscript-json/commit/1edab439e33acd787671618d33c1ec4250f523c9 commit message "Made JSON.stringify comptible with javascript JSON" (sic) was encouraging.

But https://github.com/near/assemblyscript-json/blob/1edab439e33acd787671618d33c1ec4250f523c9/assembly/JSON.ts#L85 doesn't seem to expose stringify(), from what I can tell.

And even encoder.stringify() mentioned at https://github.com/near/assemblyscript-json/blob/1edab439e33acd787671618d33c1ec4250f523c9/README.md#encoding-json doesn't seem to be available.

What am I misunderstanding? Thanks!

ryancwalsh avatar Nov 30 '21 17:11 ryancwalsh

I'd use @serial-as/json. See https://github.com/gagdiez/serial-as/tree/main/json

willemneal avatar Nov 30 '21 17:11 willemneal

@willemneal Thanks. I also had found https://www.npmjs.com/package/json-as (which I guess I will use) but felt inclined to rely on a NEAR repo instead (this one).

ryancwalsh avatar Nov 30 '21 18:11 ryancwalsh

So this entire module can't be used for JSON.stringify(obj) ?

mariusa avatar Nov 15 '22 14:11 mariusa

See the link above serial-as/json:

import * as JSON from '@serial-as/json'

@serializable
class Pair{
  x: i32 = 0,
  y: i32 = 0
}

let pair: Pair = {x:1, y:2}

// `serialized` is the string "{"x":1,"y":2}"
let serialized: string = JSON.stringify(object)  

willemneal avatar Nov 15 '22 15:11 willemneal

Thanks! So there are 3 npm modules for JSON support in assemblyscript (rather than being built-in)

https://www.npmjs.com/package/assemblyscript-json https://www.npmjs.com/package/json-as https://www.npmjs.com/package/@serial-as/json

What a mess :(

mariusa avatar Nov 15 '22 15:11 mariusa

The serial-as still uses this library for the JSON types, but rather is part of a serializing framework. It should be part of the language, to match with JS, but any of these libraries do work relatively well.

willemneal avatar Nov 15 '22 15:11 willemneal

Thanks again! Saw that json-as requires a class defined for each object property. Does serial-as too? (feel free to answer in https://github.com/gagdiez/serial-as/issues/38 )

mariusa avatar Nov 15 '22 16:11 mariusa

@mariusa, json-as used to generate its own classes so that you could create a Object Literal which would then be replaced by the generated class, but that broke as AS updated. Working on re-implementing that feature

JairusSW avatar Dec 07 '22 06:12 JairusSW