How can I set JSON into a variable from a local url

10,437

Solution 1

To retrieve the JSON string from a server use XMLHttpRequest object as described in this reference:

http://developer.mozilla.org/en/XMLHttpRequest

You'll find that it's quite involved with all the unseen things you need to account and check for. Thus libraries like jQuery.

To convert the JSON string to a javascript object, use JSON.parse(). Here's the reference:

http://developer.mozilla.org/En/Using_native_JSON

Here's an example:

function readJSON(file) {
    var request = new XMLHttpRequest();
    request.open('GET', file, false);
    request.send(null);
    if (request.status == 200)
        return request.responseText;
};

var myObject = JSON.parse(readJSON('/local/path/to/json'));

EDIT #2: Thanks for editing in this example, Chase. A word of warning. It is not a good idea to make the open() method a synchronous call by using false in the 3rd parm. AJAX is intentionally designed for asynchronous use, and to make a synchronous call invites lock ups. As one who used to think there was a place for synchronous calls, I now find there's always a better way to get it done asynchronously. Word to the wise.

Solution 2

I you're familiar with jQuery, this is a drop-in replacement for $.ajax:

Script:

function ajax( uri, settings ) {
    var ajax = new window.XMLHttpRequest(),
        data = settings.type == 'GET' ? '' : settings.data,
        async = settings.async ? settings.async : false;
        uri = settings.type == 'GET' ? uri + ( settings.data ? '?' + settings.data : '' ) : uri;

    ajax.onreadystatechange = function () {
        if ( ajax.readyState == 4 ) { //response ready
            if ( ajax.status == 200 ) { //success
                if ( settings.success ) settings.success( ajax.responseText, ajax.statusText );
                if ( settings.complete ) settings.complete( ajax, ajax.statusText );
            } else {
                if ( settings.error ) settings.error( ajax, ajax.status, ajax.statusText );
            };
        };
    };

    ajax.open( settings.type, uri, async );

    if ( settings.headers ) {
        for ( var header in settings.headers ) {
            ajax.setRequestHeader( header, settings.headers[header] );
        };
    };

    ajax.send( data );
};

Call it just like jQuery:

ajax( '/local/path/to/json', {
    "type": "GET", //or "POST"
    //"data": "<query string>", //if POST
    "success": function ( data, status ) {
        var myJson = window.JSON.parse( data );
    },
    "error": function ( response, status, error ) {
        // handle error
    }
} );

Solution 3

Please have a look at be below code snap which will on in all browsers, thanks

    function getJSONData(jsonurl) {
        var req = null;
        if (window.XMLHttpRequest) {
            req = new XMLHttpRequest();
        }
        else if (window.ActiveXObject) {
            try {
                req = new ActiveXObject("Msxml2.XMLHTTP");
            }
            catch (e) {
                try {
                    req = new ActiveXObject("Microsoft.XMLHTTP");
                }
                catch (e) { }
            }
        }
        req.open('GET', jsonurl, false);
        req.send(null);
        return req.status == 200 ? req.responseText : 'Error occurred';
    }
    var jsonData = JSON.parse(getJSONData('/local/path/to/json'));
    alert(getJSONData('/local/path/to/json'));

Hope this will be very helpful, thanks for your time

Share:
10,437

Related videos on Youtube

Chase Florell
Author by

Chase Florell

I'm a developer in BC Canada and one of the owners of Flo Media Group Inc. I work primarily in C# .NET, Xamarin, HTML5 and Javascript, and I'm also very passionate about DevOps, and have been known to sling my fair share of PowerShell. When I'm not coding, I'm enjoying time with my wonderful wife and children, riding my motorcycle, camping in the summer months, snowboarding in the winter, or maybe just a round at the Golf Course. I Blog Here, and I'm also on Linkedin Contact Me

Updated on June 04, 2022

Comments

  • Chase Florell
    Chase Florell almost 2 years

    Evidently jQuery has made me dumb.

    I've got a local url that serves up raw JSON, and I can't figure out how to consume that json from within my method without using jQuery.

    Here's how I know to do it WITH jQuery

    var myJson;
    $.getJSON('/local/path/to/json', function (data) { 
        myJson = data; 
    });
    
    // Now I can use myJson in a method.
    
    • Alnitak
      Alnitak over 12 years
      and please define "local". Do you mean file:///, or http://localhost/, or something else?
    • sdleihssirhc
      sdleihssirhc
      @ChaseFlorell You'll need to use AJAX.
    • Chase Florell
      Chase Florell
      @Alnitak, local url http://localhost/local/path/to/json
    • Alnitak
      Alnitak
      @ChaseFlorell right, so you still need to use AJAX. And if you still have jQuery in the project you might as well use it.