Parse JSON from local url with JQuery

16,423

Solution 1

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.

Solution 2

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

Edit: To parse it you can use jQuery.parseJSON

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

Solution 3

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

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

Solution 4

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:

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

Solution 5

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

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

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

etc.

Share:
16,423
Galip
Author by

Galip

Updated on June 04, 2022

Comments

  • Galip
    Galip almost 2 years

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

    • Pointy
      Pointy over 12 years
      So is the JSON file stored on your web server (where your jQuery site is hosted)? Not clear what exactly you mean by "local URL".
    • Galip
      Galip over 12 years
      I mean that the request url is local. It's a file that runs locally and accepts requests and sends back responses in json format.
    • Pointy
      Pointy over 12 years
      So like a "file://" URL? Well there may be some difficulty with that because browsers are starting to consider the local system not trustworthy, as if each different "file://" URL is a separate domain. Also, if your actual website is served from a real server ("http://") then you will be denied access to "file:" URLs.
  • Galip
    Galip over 12 years
    it was just an example, my question is mainly about how to parse. You can use some other json output if you want. But thanks anyway, i'll let it now to my project partner who works on the output part :)) edit: I validated the json output in my question just for the record ;)
  • Gaute Løken
    Gaute Løken over 12 years
    Much better json updated in OP =). However you can still improve it a bit by letting your floats be numerics, ie. "batteryLevel" : 30.0, rather than "30.0". Sadly native json, which jQuery requires (by default) is a bit strict, and you can't pass a Date constructor. See this for my investigations into this: bugs.jquery.com/ticket/8671. Ps: Feel free to upvote my answer if it's usefull to you.
  • Gaute Løken
    Gaute Løken over 12 years
    Unlike the other answers I've assumed your challenge was with parsing, not with ajax.
  • Galip
    Galip over 12 years
    i think i didn't make myself clear enough, but that's my mistake :) anyways i think i can handle it from here. Thanks for your help :)