JSON Basics: What You Need to Know

What is JSON, and what can it do? In this tutorial you learn how to use JSON to easily move data around the web. You also look at how to work with JSON using both JavaScript and PHP.

JSON Basics: What You Need to Know

If you've developed websites or web apps at all, you've probably heard of JSON, at least in passing. But what exactly is JSON? What can it do, and how do you use it?

In this tutorial you'll learn the basics of JSON. You'll look at the following topics:

  • What JSON does
  • The kinds of things JSON is used for
  • How to create JSON strings
  • A simple JSON example
  • How JSON compares to XML, and
  • How to work with JSON using both JavaScript and PHP.

Let's get started!

What is JSON?

JSON is a simple, text-based way to store and transmit structured data. By using a simple syntax, you can easily store anything from a single number through to strings, arrays, and objects using nothing but a string of plain text. You can also nest arrays and objects, allowing you to create complex data structures.

Once you've created your JSON string, it's easy to send it to another application or computer, because it's just plain text.

JSON has a lot of advantages:

  • It's compact
  • It's easy for both computers and people to read and write
  • It maps very easily onto the data structures used by most programming languages (numbers, strings, booleans, nulls, arrays and associative arrays)
  • Nearly all programming languages contain functions or libraries that can read and write JSON structures

JSON stands for JavaScript Object Notation. As the name implies, it's based on the way you define objects (which are very similar to what you'd call associative arrays or hashes in other languages), and arrays.

What is JSON used for?

JSON is most commonly used in web applications to send data from the server to the browser. Typically you transfer JSON data using Ajax, which lets your web application exchange data and messages between the browser and the server without having to reload the page.

For example:

  1. A user clicks a product thumbnail in an online store
  2. The JavaScript running in the browser makes an Ajax request to a PHP script running on the server, passing it the ID of the clicked product
  3. The PHP script retrieves the product name, description, price, and other info from the products database, encodes the data as a JSON string, and sends the string back to the browser
  4. The JavaScript running in the browser decodes the JSON string and displays the product details in the page for the user.

You can also use JSON to send data from the browser to the server, provided the JSON string is properly encoded as a GET or POST parameter. This approach is less common, since the data sent in Ajax requests tend to be fairly simple (for example, a product ID). It's more common simply to encode the data in the URL as part of the GET request.

The jQuery JavaScript library includes some useful methods, such as getJSON() and parseJSON(), that make it easy to receive JSON-encoded data via Ajax requests.

How to write JSON strings

Writing curly bracket

Here are the basic rules for creating a JSON string:

  • A JSON string contains either an array of values, or an object (an associative array of name/value pairs).
  • An array is surrounded by square brackets, [ and ], and contains a comma-separated list of values.
  • An object is surrounded by curly brackets, { and }, and contains a comma-separated list of name/value pairs.
  • A name/value pair consists of a field name (in double quotes), followed by a colon (:), followed by the field value.
  • A value in an array or object can be:

    • A number (integer or floating point)
    • A string (in double quotes)
    • A boolean (true or false)
    • Another array (surrounded by square brackets, [ and ])
    • Another object (surrounded by curly brackets, { and })
    • The value null

To put double quotes inside strings, use the backslash character to escape the double quotes: \". You can also put control characters and hexadecimal-encoded characters in strings using the backslash, like you do in most programming languages. See the JSON website for details.

A simple JSON example

The following example shows how you might store a simple shopping cart in JSON format:

{
  "orderID": 12345,
  "shopperName": "John Smith",
  "shopperEmail": "johnsmith@example.com",
  "contents": [
    {
      "productID": 34,
      "productName": "SuperWidget",
      "quantity": 1
    },
    {
      "productID": 56,
      "productName": "WonderWidget",
      "quantity": 3
    }
  ],
  "orderCompleted": true
}

Let's break this string down:

  • At the top level, we've written curly braces ({ and }), which creates an object.
  • Inside the object, we have several name/value pairs:
    "orderID": 12345
    A property with the name "orderId" and the integer value 12345
    "shopperName": "John Smith"
    A property with the name "shopperName" and the string value "John Smith"
    "shopperEmail": "johnsmith@example.com"
    A property with the name "shopperEmail" and the string value "johnsmith@example.com"
    "contents": [ ... ]
    A property with the name "contents", whose value in an array
    "orderCompleted": true
    A property with the name "orderCompleted" and the boolean value true
  • Inside the "contents" array, we have 2 objects representing individual order lines in the cart. Each object contains 3 properties: productID, productName, and quantity.

By the way, since JSON is very closely based on the notation JavaScript uses to create arrays and objects, you can take the above JSON string and create a JavaScript object from it very easily:

<script type="text/javascript">
var cart = {
  "orderID": 12345,
  "shopperName": "John Smith",
  "shopperEmail": "johnsmith@example.com",
  "contents": [
    {
      "productID": 34,
      "productName": "SuperWidget",
      "quantity": 1
    },
    {
      "productID": 56,
      "productName": "WonderWidget",
      "quantity": 3
    }
  ],
  "orderCompleted": true
};
</script>

JSON vs. XML

Sword fight

In many ways, you can think of JSON as an alternative to XML — at least in terms of web applications. The Ajax concept (Asynchronous JavaScript And XML) originally used XML to transmit data between server and browser, but in recent years JSON has become a more popular way to carry Ajax data.

While XML is a tried-and-tested technology and is used in a huge range of applications, JSON's advantages are that it tends to be more compact than XML, and easier to read and write.

Here's the previous JSON example written as XML instead:

<object>
  <property>
    <key>orderID</key>
    <number>12345</number>
  </property>
  <property>
    <key>shopperName</key>
    <string>John Smith</string>
  </property>
  <property>
    <key>shopperEmail</key>
    <string>johnsmith@example.com</string>
  </property>
  <property>
    <key>contents</key>
    <array>
      <object>
        <property>
          <key>productID</key>
          <number>34</number>
        </property>
        <property>
          <key>productName</key>
          <string>SuperWidget</string>
        </property>
        <property>
          <key>quantity</key>
          <number>1</number>
        </property>        
      </object>
      <object>
        <property>
          <key>productID</key>
          <number>56</number>
        </property>
        <property>
          <key>productName</key>
          <string>WonderWidget</string>
        </property>
        <property>
          <key>quantity</key>
          <number>3</number>
        </property> 
      </object>
    </array>
  </property>
  <property>
    <key>orderCompleted</key>
    <boolean>true</boolean>
  </property>  
</object>

As you can see, this XML version is a fair bit longer. In fact it's 1,128 characters long, whereas the JSON version is only 323 characters long. The XML version is also harder to read.

This is quite an extreme example, and it's common to write XML in a less verbose format than this. However, even compact XML formats usually take up more space than their JSON equivalents.

How to create and read JSON strings in JavaScript

JSON logo and JavaScript

JSON might be a simple format, but it's obviously fairly tedious to write JSON strings by hand. What's more, you often need to be able to take a JSON string, and convert its contents into a variable that can be used by your code.

Fortunately, most programming languages give you tools that can easily turn variables into JSON strings, and vice-versa. The basic idea is as follows:

  • To create a JSON string, you start with a variable containing some data, then pass it through a function to turn that data into a JSON string.
  • To read a JSON string, you start with a JSON string representing some data, then pass it through a function to create a variable containing the data.

Let's take a look at how to create and read JSON strings in JavaScript.

Creating a JSON string from a JavaScript variable

JavaScript contains a built-in method, JSON.stringify(), that takes a JavaScript variable and outputs a JSON string representing the variable's contents. For example, let's create a JavaScript object containing our cart data from earlier, then create a JSON string from that object:

<script type="text/javascript">

var cart = {
  "orderID": 12345,
  "shopperName": "John Smith",
  "shopperEmail": "johnsmith@example.com",
  "contents": [
    {
      "productID": 34,
      "productName": "SuperWidget",
      "quantity": 1
    },
    {
      "productID": 56,
      "productName": "WonderWidget",
      "quantity": 3
    }
  ],
  "orderCompleted": true
};

alert ( JSON.stringify( cart ) ); 

</script>

This produces the output:


{"orderID":12345,"shopperName":"John Smith","shopperEmail":"johnsmith@example.com",
"contents":[{"productID":34,"productName":"SuperWidget","quantity":1},
{"productID":56,"productName":"WonderWidget","quantity":3}],
"orderCompleted":true}

Notice that JSON.stringify() outputs JSON strings with all whitespace removed. It's harder to read, but it makes the string more compact for sending around the web.

Creating a JavaScript variable from a JSON string

There are quite a few ways to parse a JSON string in JavaScript, but the safest and most reliable way is to use JavaScript's built-in JSON.parse() method. This takes a JSON string and returns a JavaScript object or array containing the JSON data. Here's an example:

<script type="text/javascript">

var jsonString = '                          \
{                                           \
  "orderID": 12345,                         \
  "shopperName": "John Smith",              \
  "shopperEmail": "johnsmith@example.com",  \
  "contents": [                             \
    {                                       \
      "productID": 34,                      \
      "productName": "SuperWidget",         \
      "quantity": 1                         \
    },                                      \
    {                                       \
      "productID": 56,                      \
      "productName": "WonderWidget",        \
      "quantity": 3                         \
    }                                       \
  ],                                        \
  "orderCompleted": true                    \
}                                           \
';

var cart = JSON.parse ( jsonString );

alert ( cart.shopperEmail );
alert ( cart.contents[1].productName );

</script>

Here we've created a variable, jsonString, that holds the JSON string for our shopping cart example. Then we've passed this string through JSON.parse() to create an object holding the JSON data, which we store in cart. We then check the conversion worked by displaying the contents of the object's shopperEmail property, as well as the value of the productName property of the second object in the contents array.

This displays the following output:


johnsmith@example.com
WonderWidget

In a real-world online store application, your JavaScript would likely receive the shopping cart JSON string as an Ajax response from a server script, pass the string to JSON.parse(), then use the data in the resulting object to display the cart to the user in the page.

JSON.stringify() and JSON.parse() can do other things too, such as allowing callback functions to do their own custom conversions of certain values. This is handy for things like converting a date value in a JSON string to a proper JavaScript Date object. Find out more about JavaScript's JSON methods.

How to create and read JSON strings in PHP

JSON logo and PHP

PHP, like JavaScript, has functions that can convert variables to JSON strings and vice-versa. Let's take a look at them.

Creating a JSON string from a PHP variable

json_encode() takes a PHP variable and returns a JSON string representing the variable. Here's our shopping cart example written in PHP:

<?php
$cart = array(
  "orderID" => 12345,
  "shopperName" => "John Smith",
  "shopperEmail" => "johnsmith@example.com",
  "contents" => array(
    array(
      "productID" => 34,
      "productName" => "SuperWidget",
      "quantity" => 1
    ),
    array(
      "productID" => 56,
      "productName" => "WonderWidget",
      "quantity" => 3
    )
  ),
  "orderCompleted" => true
);

echo json_encode( $cart );
?>

This produces exactly the same output as our JavaScript example — a valid JSON string representing the variable's contents:


{"orderID":12345,"shopperName":"John Smith","shopperEmail":"johnsmith@example.com","contents":[{"productID":34,"productName":"SuperWidget","quantity":1},{"productID":56,"productName":"WonderWidget","quantity":3}],"orderCompleted":true}

In a real-world online store, your PHP script would send this JSON string as part of the Ajax response back to the browser, where the JavaScript code would use JSON.parse() to turn the string back into a variable so it can display the cart's contents to the shopper.

You can also pass various flags as a second argument to json_encode(). These let you do things like encode certain special characters using hex notation to make the string more portable, and force empty and indexed arrays to be encoded as objects (associative arrays). Find out more.

Creating a PHP variable from a JSON string

To go the other way and convert a JSON string into a PHP variable, you use — you guessed it — json_decode(). Let's rewrite our JavaScript JSON.parse() example in PHP:

<?php
$jsonString = '
{                                           
  "orderID": 12345,                         
  "shopperName": "John Smith",              
  "shopperEmail": "johnsmith@example.com",  
  "contents": [                             
    {                                       
      "productID": 34,                      
      "productName": "SuperWidget",         
      "quantity": 1                        
    },                                      
    {                                       
      "productID": 56,                      
      "productName": "WonderWidget",        
      "quantity": 3                         
    }                                       
  ],                                        
  "orderCompleted": true                    
}                                           
';

$cart = json_decode( $jsonString );
echo $cart->shopperEmail . "<br>";
echo $cart->contents[1]->productName . "<br>";
?>

As with the JavaScript version, this produces the following output:


johnsmith@example.com
WonderWidget

By default, json_decode() returns JSON "objects" as actual PHP objects. These are generic PHP objects of the stdClass class. That's why we used -> to access the objects' properties in the example above.

If you'd rather return JSON objects as PHP associative arrays, just pass true as a second argument to json_decode(). For example:

$cart = json_decode( $jsonString, true );
echo $cart["shopperEmail"] . "<br>";
echo $cart["contents"][1]["productName"] . "<br>";

This displays the same output:


johnsmith@example.com
WonderWidget

You can also pass other arguments to json_decode() to specify things like the recursion depth and how to handle large integers. Find out more.

Summary

In this tutorial you've learned the basics of JSON. You've looked at:

  • What JSON is, and what it's used for
  • The syntax of JSON strings
  • A simple example of a JSON string
  • How JSON compares to XML, and
  • How to read and write JSON strings in both JavaScript and PHP.

Although simple to understand and use, JSON is a very useful and flexible way to transfer data between applications and computers, particularly when sending Ajax data from server to browser. If you're planning to write Ajax applications then you'll no doubt find that JSON is an essential tool in your toolbox.

I hope you enjoyed reading this tutorial. Happy coding!

Follow Elated

Related articles

Responses to this article

7 responses (oldest first):

01-Apr-11 17:53
I have been reading ans studying your article on Json and it is really good but I can't seem to parse and display the individual elements of the following. I am pasting the json and the code I'm trying to use. I modified it from your example but of course I'm doing something wrong.

I would rather not use the 'true' to create the array but would like to know how to parse this json both ways.

Thank You for your help,

Ken




$jsonString = '
{
"Report":{"@attributes":{
"Name":"rpt_Exception"
},
"table1":{
"@attributes":{
"textbox1":"Car dealership",
"textbox15":"R&R Data: 3\/31\/2011 8:17:42 AM"
},
"grp_Account_Collection":
{
"grp_Account":[
{
"textbox17":"TOTAL for Acct 205 => 10 Days",
"textbox21":"819,593"
},
"Grp_Carline_Collection":{"Grp_Carline":
{
"Detail_Collection":
{
"Detail":[
{"@attributes":
{
"Account":"205",
"Description":"Contracts In Transit",
"ControlNumber":"8888",
"AgeInDays":"95",
"Balance":"2,003.32",
"CustomerNo":"99999",
"CustomerName":"Davis",
"BankNameOrCarLine":"Auto Finance"
}
},
{"@attributes":
{
"Account":"205",
"Description":"Contracts In Transit",
"ControlNumber":"7777",
"AgeInDays":"82",
"Balance":"(1,123.34)",
"CustomerNo":"66666",
"CustomerName":"Holmes",
"BankNameOrCarLine":"C A C"
}
},
],
}
}
],
}
}
}
}
';

$cart = json_decode( $jsonString,true );
print_r($cart);
04-Apr-11 02:38
@kvandiver: This tool is very useful

http://www.jsonlint.com/

As you can see, the problem is on line 17 of your JSON. You've created an array called "grp_Account", so every item within that array needs to be a single value (such as another array or an object). However, on line 17 you have not a single value, but a name/value pair ("Grp_Carline_Collection": {...}).

Hope that helps!
Matt
28-Apr-11 16:07
Aw, this article was going so well until I got to the XML section. No one in their right mind would write XML like that! In XML, the element names themselves are the keys.

Something along these lines would be the correct way:


<cart>
<orderId>12345</orderId>
<shopperName>John Smith</shopperName>
<shopperEmail>johnsmith@example.com</shopperEmail>
<orderCompleted>true</orderCompleted>

<contents>
<product id="34" quantity="1">SuperWidget</product>
<product id="56" quantity="3">WonderWidget</product>
</contents>
</cart>


This turns out to be 286 characters without spaces, as opposed to 236 for JSON. Not a huge difference. (Personally I still prefer JSON since it's dead simple to parse and work with in Javascript/PHP.)
28-Apr-11 19:20
@sockpuppet: Agreed. I was just trying to show the extreme case with XML. There are many ways to write XML, and there are also some cases where avoiding attributes makes sense. But in most situations I would definitely use your more compact version.

Here's a good discussion:

http://nedbatchelder.com/blog/200412/elements_vs_attributes.html

The point still stands though: JSON is generally more compact than XML.

Edit: I've added a note to the article to clarify. Thanks!

[Edited by matt on 28-Apr-11 19:36]
21-Apr-12 09:45
Matt ,

I love your tutorials man!
04-May-12 05:27
@tonyb67: Thanks
22-Mar-13 14:49
I was wondering if you can help with this. I am sending a jquery:


var jsonData = $.ajax({
type: "GET",
url: "http://127.0.0.1:8080/getData.php",
dataType:"json",
async: false,
error: function(xhr, s, t) {
alert("xhr: " + xhr.status + " " + xhr.statusText + " " + s + " " + t);
}
}).responseText;



but get an error. which is:
...NS_ERROR_FAILURE http://code.jquery.com/jquery-1.9.1.js
...send line 8526 data: no
It is failing in sending the request, looks like. Any clue
what could be wrong or how to fix the problem?
getdata.php simply reads a file in json syntax and sends
it back:

<?php

$string = file_get_contents("enroll-1.json");
echo $string;

?>
If its' failing in the send then it can't be json syntax problem. It should at least send the request.
I ahve spent over 8 hours trygint to figure this out, any help
is greatly appreciated.

Thanks.

Post a response

Want to add a comment, or ask a question about this article? Post a response.

To post responses you need to be a member. Not a member yet? Signing up is free, easy and only takes a minute. Sign up now.

Top of Page