How does Javascript differentiate between Json Objects and String?

I was reading a code snippet and figuring out how it works when this weird javascript problem came up.

In their javascript they called

var apiUrl = '/api/v1/pin/?format=json&order_by=-id&offset='+String(offset);
$.get(apiUrl, function(pins) { 
    for (...; i < pins.objects.length; i++) ... // works fine

their api returns this json format:

{"meta": {"limit": 50, "next": "?limit=50&format=json&order_by=-id&offset=60", "offset":    
10, "previous": null, "total_count": 79}, "objects": [ {...},{...}, ... ]}

I tried to mimic it but the $.get never accepted my simplified json string.

// my attempt
$.get(myApiUrl, function(pins) { 
    for (...; i < pins.objects.length; i++) ... // ERROR: undefined length

My Json string is in the similar but shortened format.

{"objects": [{...},{...}, ... ]}

I couldn't get it to work until I googled the $.getJson() command. I am just wondering why their javascript code works with just $.get whereas mine has to use $.getJson??

Is it some kind of header you can set to force javascript to read it as json?


If you don't specify content type explicitly jQuery will try to determine data type based on headers returned by server.

If you are not using JSON serializers, then verify validity of your JSON using or this, otherwise you will get an error.

Correct ContentType header for JSON is: application/json

In both cases the AJAX call returns a string. jQuery somehow has to figure out what to do with it. How it does that depends on the dataType option.

The docs call the default value Intelligent guess. So how to guess? Evaluating the Content-Type header of the response. If it's application/jsonthen jQuerywill try to create an object.

To ensure that jQuerywill always try to interpret the response as JSON you can set the dataType to json.

Need Your Help

C# PropertyInfo GetValue() returns “Object does not match target type”

c# generics getvalue

I have a project that is reading rows returned from a SQL Server View, let's call the view 'Foo', and writing these rows to a series of files. Using LINQ2SQL to reference the view in my project, r...

How to implement Type-safe COM enumerations?

delphi com delphi-5

How could i implement Type-Safe Enumerations in Delphi in a COM scenario ? Basically, i'd like to replace a set of primitive constants of a enumeration with a set of static final object references

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.