Loading a JSON file in a cocos creator project?

Loading a JSON file in a cocos creator project?
0

Note that I’m very new to this. I have a simple JSON file under assets and I want to load it in a variable like I do in other langages.

How can I do that?

Something like that:

var HeroDefault = ccs.load(“HeroDefault.json”);

I get the error that
Simulator : HeroDefault.json does not exist

When I use the simulator.

What is the best way to load a JSON file in the creator? What Am I doing wrong?

Thanks!

Hi, try this…

  1. right place:
    put u’r json file to path “assets/resources/HeroDefault.json”
    if assets not has resources sub folder, create it.
  2. Coding:
var url = cc.url.raw( 'resources/HeroDefault.json' )
cc.loader.load( url, function( err, res)
{
    cc.log( 'load['+ url +'], err['+err+'] result: ' + JSON.stringify( res ) );
});

then you will see the json file dump to log.

3 Likes

It worked, thanks alot.

how we can use the json in cocos creator 2.1.0

var t_Setsjson;

var url = cc.url.raw( ‘resources/IV_SetsJSON.json’ )

cc.loader.load( url, function( err, t_Setsjson)

{

cc.log( ‘load[’+ url +’], err[’+err+’] result: ’ + JSON.stringify( t_Setsjson ) );

});
starting its working after buid in browser getting error can u check please

after running in browser i am getting error called

Failed to load resource: the server responded with a status of 404 (Not Found) [http://localhost:7456/resources/IV_SetsJSON.json]

This is a 3 year old topic, why not start a new topic?

hi,
I just need the one line of code for reading a string containing a json and making a json object.
for e.g…
var txt = {“name”:“sam”};
var objj0 = JSON.stringify(txt);
var txt2 = objj0[“name”];
console.log(txt2);
it prints undefined in the console.
what is wrong and how can I assign the value of txt2 to another variable of type string?
thanks

because you are reading it as an object after you converted it to string

Hi,
I guess what you are trying to do is following:

var txt = '{"name":"sam"}';   //String in JSON format, please notice the single quotes surrounding the string
var obj0 = JSON.parse(txt); //Take text and create object
var txt2 = obj0["name"];
console.log(txt2); //this *should* print out "sam"

JSON.stringify(obj) takes an object and converts it to a string, but considering your purpose description, I guess you want to take a string and convert it to an object, which can be achieved by JSON.parse(string)