Search code examples
javascriptjsonjquerygetjson

Parse JSON from local url with JQuery


I have a local url where i can retrieve a json file. I also have a simple website which is build using 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.

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.

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..


Solution

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

    $.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.

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