How to load JSON data in Cocos2d-X 3.0 in javascript

给你一囗甜甜゛ 提交于 2020-01-24 13:05:22

问题


How would one load a javascript structure (object or array) from a file in Cocos2d-X 3.

My res/test.json:

{
    version:"1.0",
    data:"this is some data."
}

I'm able to load the file content like so:

var data = fileUtil.getStringFromFile('res/test.json');
cc.log(data);

What is the best way to load the javascript structure from the string? Is there a function in cocos2d-x to do this directly?


回答1:


The "standard" JSON.parse works:

var fileUtil = cc.FileUtils.getInstance();
var data = fileUtil.getStringFromFile('res/test.json');
var jData = JSON.parse(data);

But note all attribute names must be passed in quotes, otherwise the parser will fail. res/test.json must then look like this:

{
    "version":"1.0",
    "data":"this is some data."
}


来源:https://stackoverflow.com/questions/20686518/how-to-load-json-data-in-cocos2d-x-3-0-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!