javascript 使用 JQuery 从本地 url 解析 JSON

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8021022/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 02:00:20  来源:igfitidea点击:

Parse JSON from local url with JQuery

javascriptjsonjquerygetjson

提问by Galip

I have a local url where i can retrieve a json file. I also have a simple website which is build using JQuery.

我有一个本地 url,我可以在其中检索 json 文件。我还有一个使用 JQuery 构建的简单网站。

I've looked up many sites for tutorials and sample code on how to retrieve the json input and parse it so i can display it on my site. However non were helpful as i still can't make it work.

我已经在许多站点上查找了有关如何检索 json 输入并解析它的教程和示例代码,以便我可以在我的站点上显示它。但是,没有帮助,因为我仍然无法使其工作。

So as a last resort i'm going to ask stackoverflow for your help. I have a lot of java knowledge, but I'm relative new to 'web'-development and know some basics of javascript.

因此,作为最后的手段,我将向 stackoverflow 寻求帮助。我有很多 Java 知识,但我对“网络”开发相对较新,并且知道一些 javascript 基础知识。

This is a sample output of my url:

这是我的网址的示例输出:

[
    {
        "baken": "not implemented...",
        "deviceType": "Optimus 2X",
        "batteryLevel": "1.0",
        "gps": {
            "speed": 0,
            "Date": "TueNov0100: 34: 49CET2011",
            "Accuracy": 35,
            "longitude": {removed},
            "latitude": {removed},
            "Provider": "gps"
        },
        "deviceId": "4423"
    },
    {
        "baken": "notimplemented...",
        "deviceType": "iPhone",
        "batteryLevel": "30.0",
        "gps": {
            "speed": 0,
            "Date": "TueNov0116: 18: 51CET2011",
            "Accuracy": 65,
            "longitude": {removed},
            "latitude": {removed},
            "Provider": null
        },
        "deviceId": "4426"
    }
]

Hope you can help me..

希望你能帮我..

回答by skython

If you are running a local web-server and the website and the json file are served by it you can simply do:

如果您正在运行本地网络服务器并且网站和 json 文件由它提供服务,您只需执行以下操作:

$.getJSON('path/to/json/file.json', function(data) {
  document.write(data);
})

If you are just using files and no webserver you might get a problem with the origin-policy of the browser since AJAX request cannot be send via cross-domain and the origin domain is 'null' per default for request from local files.

如果您只是使用文件而不使用网络服务器,则浏览器的原始策略可能会出现问题,因为无法通过跨域发送 AJAX 请求,并且对于来自本地文件的请求,原始域默认为“空”。

If you are using Chrome you can try the --allow-file-access-from-filesparameter for developing purposes.

如果您使用 Chrome,您可以尝试使用该--allow-file-access-from-files参数进行开发。

回答by Gaute L?ken

Your URL returns invalid json. Try pasting it in jsonlint.com and validating it there and you'll see what I mean. Even the code highlighting here on stackoverflow is showing you what's wrong. :)

您的 URL 返回无效的 json。尝试将其粘贴到 jsonlint.com 并在那里进行验证,您就会明白我的意思。甚至在 stackoverflow 上突出显示的代码也向您展示出了什么问题。:)

Edit: To parse it you can use jQuery.parseJSON

编辑:要解析它,您可以使用 jQuery.parseJSON

 jQuery.parseJSON('{"foo": "goo"}');

回答by Brad G.

$.get('/some.json', function(data) {
  // data[0]["baken"] == "not implemented..."
});

See http://api.jquery.com/jQuery.get/

http://api.jquery.com/jQuery.get/

回答by Ryan

The most natural way is to allow jQuery to make an AJAX call for you once you've already entered the page. Here's an example:

最自然的方法是在您进入页面后让 jQuery 为您进行 AJAX 调用。下面是一个例子:

    $.ready(function() {

         // put your other code for page initialization here

         // set up a global object, for namespacing issues, to hold your JSON.
         // this allows your to be a good "web" citizen, because you will create
         // one object in the global space that will house your objects without
         // clobbering other global objects from other scripts, e.g., jQuery
         // makes the global objects '$' and 'jQuery' 
         myObjects = {};

         // start JSON retrieval here
         $.getJSON('/path/to/json/file.json', function(data) {
             // 'data' contains your JSON.
             // do things with it here in the context of this function.
             // then add it to your global object for later use.
             myObjects.myJson = data; 
         });

    });

The API documentation is here

API 文档在这里

回答by Hogan

You don't need to parse the json -- that is why people like it. It becomes a native JavaScript object.

您不需要解析 json —— 这就是人们喜欢它的原因。它成为原生 JavaScript 对象。

For your example if you put the results in a variable called datathen you could do things like this:

对于您的示例,如果您将结果放在一个名为的变量中,data那么您可以执行以下操作:

 data[0].deviceType // would be "Optimus 2x"
 data[0].gps.speed  // would be numeric 0

etc.

等等。