JSON – JavaScript Object Notation

→ Are you a new visitor? Please visit the page guidance for new visitors ←

JSON – JavaScript Object Notation

Nowadays web applications tend to leave more and more to the past 3rd party things like “FLASH” and adopt even more javascript for developing same things more efficiently. The reason is simple, javascript always been here, and now since the web is more interactive, you need this kind of language to interact with a server real time.

When it comes to store data in javascript, JSON is the absolute best way to do that. It is simple, lightweight and easy to learn. Once you learn it, you will use it and love it .

Wait, JSON who ?

Yes, JSON stands for javascript object notation and it is better than XML for use with Javascript (because it is not a markup language and it is lightweight). It is also easier and quicker to setup than XML on the server-side.

How does it looks?

I know what you are going to tell me: “This is a regular javascript object”. But it is not, trust me. Why ?

Difference between JSON and regular javascript object

JSON is a string representation of an object. It is an interoperable serialization format. It is not tied only to javascript. For example there are JSON serializers for .NET allowing you to serialize/deserialize .NET objects.

So it’s just a format allowing you to convert from objects to string and back which is convenient if you want to transfer them over the wire.

In JSON you must make sure that:

  • the keys are strings (i.e. enclosed in double quotes ") in JSON.
  • the values are either:
    • a string
    • a number
    • an (JSON) object
    • an array
    • true
    • false
    • null

JSON has a much more limited syntax. An example is that you are not allowed to use functions in a JSON object. Is a kind of wrapper on “JavaScript Object Notation” which forces users to obey more strict rules for defining the objects. And it does this by limiting the possible object declaration ways provided by JavaScript Object Notation feature.

As a result we have a simpler and more standardized objects which suits better on data-exchange between platforms.

JSON in php

We have functions in php that will help us encode and decode the JSON format and also debug it in case we have errors.

  • json_decode – Decodes a JSON string
  • json_encode – Returns the JSON representation of a value
  • json_last_error_msg – Returns the error string of the last json_encode() or json_decode() call
  • json_last_error – Returns the last error occurred

If you have an array called $data in php, you can encode or transform it into a JSON format like this:

Further reading

JSON Wikipedia

Introducing JSON

Request an article ←