Skip to content

JSON Basics What You Need to Know

json

A common use of JSON is to read data from a web server, and display the data in a web page.
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?
json

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

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 deo",
  "shopperEmail": "johndeo@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 deo” A property with the name “shopperName” and the string value “John deo” “shopperEmail”: “johndeo@example.com” A property with the name “shopperEmail” and the string value “johndeo@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 deo",
  "shopperEmail": "johndeo@example.com",
  "contents": [
    {
      "productID": 34,
      "productName": "SuperWidget",
      "quantity": 1
    },
    {
      "productID": 56,
      "productName": "WonderWidget",
      "quantity": 3
    }
  ],
  "orderCompleted": true
};
</script>

JSON vs. XML

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 deo</string>
  </property>
  <property>
    <key>shopperEmail</key>
    <string>johndeo@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 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 deo",
  "shopperEmail": "johndeo@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 deo","shopperEmail":"johndeo@example.com",
"contents":[{"productID":34,"productName":"SuperWidget","quantity":1},
{"productID":56,"productName":"WonderWidget","quantity":3}],
"orderCompleted":true}

Notice thatJSON.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 deo",              
  "shopperEmail": "johndeo@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:

johndeo@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.

How to create and read JSON strings in 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 deo",
  "shopperEmail" => "johndeo@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 deo","shopperEmail":"johndeo@example.com","contents":[{"productID":34,"productName":"SuperWidget","quantity":1},{"productID":56,"productName":"WonderWidget","quantity":3}],"orderCompleted":true}

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.

How to create and read JSON strings in 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
$jsonString = '
{                                           
  "orderID": 12345,                         
  "shopperName": "John deo",              
  "shopperEmail": "johndeo@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:

johndeo@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:

johndeo@example.com
WonderWidget

or 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!

1 thought on “JSON Basics What You Need to Know”

Leave a Reply

Your email address will not be published. Required fields are marked *