JQuery.parseJSON vs. jQuery.getJSON

I am new to using JSON (and for jQuery Ajax functions in general). What I'm trying to do is create a separate file containing the JSON object, point to this file, save the object as a variable, and access the properties of the object using dot notation.

jQuery.parseJSON () allows me to do what I want, but I want to take the next step, pointing to a separate file.

For example, the following behavior behaves exactly as I expected by opening a warning window that says “red”:

var test = $.parseJSON('{"simple":"red"}');
alert(test.simple);

The following indicates that points to a file containing the same JSON object does not work, opening a warning window that says "undefined":

var test = $.getJSON('simple.json');
alert(test.simple);

I obviously do not use it correctly. What is the right way to do what I'm trying to achieve here?

+5
source share
6 answers

Check out the getJSON docs: http://api.jquery.com/jQuery.getJSON/

you should do something like:

$.getJSON('simple.json', function(data) {
  alert(data.simple);
});

always pays to read API docs

+7
source

I think you misunderstood getJSON. It does not return a JSON object, but is a shorthand for parsing response text from an AJAX request as JSON.

When you call getJSON, you are actually executing an asynchronous request. When you raise a warning, the request has not yet returned.

Try:

var test;
$.getJSON('simple.json', {}, function(data) {
  test = data;
  alert(test.simple);
});

Shabba: http://api.jquery.com/jQuery.getJSON/

+6
source

$.getJSON HTTP GET .

$.getJSON('simple.json', function(data) {
    alert(data.simple);
});

, jQuery 1.5 , jqXHR.

$.getJSON('simple.json')
 .success(function(data) {
    alert(data.simple);
 });
+2

getJson parseJson

jQuery.getJSON() JSON- HTTP- GET.

$.getJSON( "ajax/test.json", function( data ) {  
    $.each( data, function( key, val ) {    
        //your actions
});

jQuery.parseJSON() JSON JavaScript.

var obj = jQuery.parseJSON( '{ "name": "John" }' );

$.getJSON() JSON- GET HTTP URL-, . $.parseJSON() JavaScript, JSON.

+1

getJSON ,

JSON- GET HTTP.

0

$.get('path/to/file', function(data) { my_variable = data; }, "json" );

0
source

All Articles