tags:

views:

3662

answers:

9

Sorry for asking what may well seem like a dumb question. I've looked on wikipedia and Googled it and read the official documentation, but I've still not got to the point where I really understand what JSON is, and why I'd use it.

I have been building applications using PHP, MySQL and Javascript / HTML for a while, and if JSON can do something to make my life easier or my code better or my user interface better, then I'd like to know about it. Can someone give me a succinct explanation?

Thanks,

Ben

+65  A: 

JSON (JavaScript Object Notation) is a lightweight format that is used for data interchanging. It is also a subset of JavaScript's Object Notation (the way objects are built in JavaScript)


An example of where this is used is web services responses. In the 'old' days, web services used XML as their primary data format for transmitting back data, but since JSON appeared (The JSON format is specified in RFC 4627 by Douglas Crockford), it has been the preferred format because it is much more lightweight

You can find a lot more info on one of Crockford's sites here

JSON is built on two structures:

  • A collection of name/value pairs. In various languages, this is realized as an object, record, struct, dictionary, hash table, keyed list, or associative array.
  • An ordered list of values. In most languages, this is realized as an array, vector, list, or sequence.

JSON Structure



alt text

alt text

alt text

alt text

alt text

Here is an example of JSON data:

{
     "firstName": "John",
     "lastName": "Smith",
     "address": {
         "streetAddress": "21 2nd Street",
         "city": "New York",
         "state": "NY",
         "postalCode": 10021
     },
     "phoneNumbers": [
         "212 555-1234",
         "646 555-4567"
     ]
 }

JSON in JavaScript

When working with JSON and JavaScript, you may be tempted to use the eval function to evaluate the result returned in the callback, but this is not suggested due to security reasons (malicious data can be sent from the server to the client and then evaled in the client script with harmful effects).

Therefore, one must always try to use Crockford's script that checks for a valid JSON before evaluating it. Link to the script explanation is found here and here is a direct link to the js file.

Example on how to use the JSON Parser (with the json from the above code snippet):

//The callback function that will be executed once data is received from the server
var callback = function (result) {
    var johnny = JSON.parse(result);
    //Now, the variable 'johnny' is an object that contains all of the properties 
    //from the above code snippet (the json example)
    alert(johnny.firstName + ' ' + johnny.lastName); //Will alert 'John Smith'
};

The JSON Parser also offers another very useful method, stringify. This method accepts a JavaScript object as a parameter, and outputs back a string with JSON format. This is useful for when you want to send data back to the server:

var anObject = {name: "Andreas", surname : "Grech", age : 20};
var jsonFormat = JSON.stringify(anObject);
//The above method will output this: {"name":"Andreas","surname":"Grech","age":20}

The above two methods (parse and stringify) also take a second parameter, which is a function that will be called for every key and value at every level of the final result, and each value will be replaced by result of your inputted function. (More on this here)

Btw, for all of you out there who think JSON is just for JavaScript, check out this post that explains and confirms otherwise.


References

Andreas Grech
Regardless of the way information is serialized, you're going to have a parser, right? Therefore, who cares what format you use to transmit data if its implementation details are going to be abstracted away.
Horace Loeb
Well actually, if you're transmitting data to and fro the client and server, I think it's pretty important to be careful of your response sizes.
Andreas Grech
And it's only been around for two years. Seems like a lot longer than that.
le dorfier
+2  A: 

JSON is JavaScript Object Notation. It is a much-more compact way of transmitting sets of data across network connections as compared to XML. I suggest JSON be used in any AJAX-like applications where XML would otherwise be the "recommended" option. The verbosity of XML will add to download time and increased bandwidth consumption ($$$). You can accomplish the same effect with JSON and its mark-up is almost exclusively dedicated to the data itself and not the underlying structure.

Nolte Burke
+4  A: 

the common short answer is: if you are using AJAX to make data requests, you can easily send and return objects as JSON strings. Available extensions for Javascript support toJSON() calls on all javascript types for sending data to the server in an AJAX request. AJAX responses can return objects as JSON strings which can be converted into Javascript objects by a simple eval call, e.g. if the AJAX function someAjaxFunctionCallReturningJson returned

"{ \"FirstName\" : \"Fred\", \"LastName\" : \"Flintstone\" }"

you could write in Javascript

var obj = eval("(" + someAjaxFunctionCallReturningJson().value + ")");
alert(obj.FirstName);
alert(obj.LastName);

JSON can also be used for web service payloads et al, but it is really convenient for AJAX results.

Steven A. Lowe
A: 

We have to do a project on college and we faced a very big problem, it is called Same Origin Policy. Amog other things, it makes that your XMLHttpRequest method from Javascript can't make requests to domains other than the domain that your site is on.

For example you can't make request to www.otherexample.com if your site is on www.example.com. JSONRequest allows that, but you will get result in JSON format if that site allows that(for example it has a web service that returns messages in JSON). That is one problem where you could use JSON perhaps.

Here is something practical: Yahoo JSON

gljivar
+10  A: 

In short - JSON is a way of serializing in such a way, that it becomes JavaScript code. When executed (with eval or otherwise), this code creates and returns a JavaScript object which contains the data you serialized. This is available because JavaScript allows the following syntax:

var MyArray = [ 1, 2, 3, 4]; // MyArray is now an array with 4 elements
var MyObject = {
    'StringProperty' : 'Value',
    'IntProperty' : 12,
    'ArrayProperty' : [ 1, 2, 3],
    'ObjectProperty' : { 'SubObjectProperty': 'SomeValue' }
}; // MyObject is now an object with property values set.

You can use this for several purposes. For one, it's a comfortable way to pass data from your server backend to your JavaScript code. Thus, this is often used in AJAX.

You can also use it as a standalone serialization mechanism, which is simpler and takes up less space than XML. Many libraries exists that allow you to serialize and deserialize objects in JSON for various programming languages.

Vilx-
+3  A: 

There are no such things as dumb questions... just dumb people. ;)

I'm in a situation similar to you. Here is a very quick and concise write-up.

http://secretgeek.net/json_3mins.asp

mson
+1  A: 

I like JSON mainly because it's so terse. For web content that can be gzipped, this isn't necessarily a big deal (hence why xhtml is so popular). But there are occasions where this can be beneficial.

For example, for one project I was transmitting information that needed to be serialized and transmitted via XMPP. Since most servers will limit the amount of data you can transmit in a single message, I found it helpful to use JSON over the obvious alternative, XML.

As an added bonus, if you're familiar with Python or Javascript, you already pretty much know JSON and can interpret it without much training at all.

Jason Baker
A: 

I have used Yahoo JSON to implement this little features in my blog at http://www.coolaspdotnetcode.com/Web/JsonExample.aspx. JSON rocks!

Shiva
A: 

It's very simple. JSON stands for Java Script Object Notation. Think of it as an alternative to using XML for transferring data between software components.

For example, I recently wrote a bunch of web services that returned JSON, and some Javascript developers then wrote code which called the services and consumed the information returned in that format.

Jon