如何在javascript中使用JSON文件
首先,我是Javascript领域的新手。我有一个JSON文件,如下所示:
First off, I am a newcomer to the Javascript realm. I have a JSON file, such as the following:
{"markers": [
{
"abbreviation": "SPA",
"latitude":-13.32,
"longitude":-89.99,
"markerImage": "flags/us.png",
"information": "South Pole",
},
.... lots more of these in between ....
{
"abbreviation": "ALE",
"latitude":-62.5,
"longitude":82.5,
"markerImage": "flags/us.png",
"information": "Alert",
},
] }
我有我已经做了很多研究,我怎么能把这个文件带回我的脚本,只是为了找到将字符串编码成JSON文件的方法。基本上,我想通过javascript读取此文件,类似这样......(我知道这不是你的编码方式)
I have been doing a lot of research as to how I can bring this file back into my script only to find ways to encode strings into JSON files. Basically, I want to read this file through javascript, something like this... (I know this isn't how you code)
object data = filename.json
document.write(data.markers.abbreviation[1])
有人可以告诉我如何做到这一点的明确指示。记住,我是一个新手,需要具体细节,因为我不能与javascript行话相提并论。
Can someone please give me clear instruction on how to go about doing this. Remember, I am a newcomer and need specifics since I'm not up to par with the javascript jargon.
首先你需要文件句柄。你需要通过ajax或服务器端行为来获取它。
First you need a handle on a file. You need to get it somehow either through ajax or through server-side behaviour.
你需要告诉使用文件的位置。你打算如何获得它以及你使用的服务器代码。
You need to tell use where the file is. How you plan to get it and what serverside code your using.
一旦你有了你可以使用 JSON.parse(string)
就可以了。如果您需要支持旧浏览器,可以包含 json2.js 文件。
Once you have you can use JSON.parse(string)
on it. You can include the json2.js file if you need to support older browsers.
如果您使用jQuery,您还可以尝试 jQuery.parseJSON
用于解析。
If you use jQuery you can also try jQuery.parseJSON
for parsing instead.
An option for remotely getting json would be using jQuery.getJSON
要加载它,您可以使用JSONP 或某种具有ajax功能的库,如 jQuery.ajax
或 的Ajax.Request
。它可以在原始的javascript中完成,但这只是丑陋并重新发明轮子。
To load it you can either use JSONP or some kind of library with ajax functionality like jQuery.ajax
or Ajax.Request
. It can be done in raw javascript but that's just ugly and re-inventing the wheel.
$.getJSON("document.json", function(data) {
console.log(data);
// data is a JavaScript object now. Handle it as such
});