开发者

Creating a json obj from a string when working without a net connection?

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


Simple as this:

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


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.


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"}');
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜