Correct Way to parse Json file into TypeScript Array Object

Correct Way to parse Json file into TypeScript Array Object
0

#1

Hi Dear Community,
I’m trying to do a JsonParser for Typescript, by this way.
import JsonParser from “…/JsonParser”;

const { ccclass, property } = cc._decorator;

@ccclass
export default class Grid extends cc.Component {
cellCards: CellCard[] = new Array();

onLoad() {
    this.loadJson();
}

loadJson() {
    this.cellCards = JsonParser.parse<CellCard>("/resources/grid.json");
    this.cellCards.forEach(element => {
        console.log(element.type);
    });
}

}

interface CellCard {
type: Type;
}

enum Type {
WOLF,
BOSS,
MONEY
}

image
Thats not working, but it prints loading Json. I think it is because the callback function is running after the function make the return. Do you know what is going on?

Whats the correct way to parse a Json file to a Typescript array objects?


#2

Yes, you need to either wrap the loadRes with async/await or return via a callback cb(err, res), not a normal return.