tags:

views:

20

answers:

3

Hi,

I have a json object returned from a third party api, it looks like:

{"version":"1.0","encoding":"UTF-8"}

I'm going to be working on my project without a network connection, so I have to do everything locally. How can I create an instance of a json object locally for testing? Say I copy the above string, can I do something like:

var json = null;
if (debugging_locally) {
    json = new jsonObj('{"version":"1.0","encoding":"UTF-8"}');
}
else {
    json = doAjaxCall();
}

doStuffWithJsonObj(json);

so I just want to create a json object from a stored string if debugging locally - how can I do that?

Thanks

+3  A: 

Simple as this:

if (debugging_locally) {
    json = {"version":"1.0","encoding":"UTF-8"};
}
Khnle
A: 

JSON is valid Javascript syntax.

Therefore, you can paste the JSON directly into the Javascript (not as a string) and assign it to a variable.

SLaks
A: 

Take a look at Resig's post as well. He covers some new JSON parsing capabilities that are currently in the JS engines of Safari, WebKit, Chrome, Firefox.

This way you can test a JSON string that you will be expecting from a web-service, your API etc.
eg.

instead of:

json = new jsonObj('{"version":"1.0","encoding":"UTF-8"}');

you could do:

json = JSON.parse('{"version":"1.0","encoding":"UTF-8"}');
Justin