JSON (Data Interchange Format)

JSON general

JSON (JavaScript Object Notation) is one of the lighter text-based open standards designed for readable data exchange. The data file extension in JSON format is .json, while the meta tag (MIME format) is application/json.

JSON is a format that is slowly replacing XML because it has several advantages over XML. JSON does not use tags and therefore has shorter code that is easier to write and more understandable to read. Although the most important advantage of JSON over XML is that JSON is parsed through a standard JavaScript function while XML is parsed through an XML parser.

Data types

The following data types can be used within the JSON structure:

  • Number (JavaScript double precision floating point format, implementation dependent)
  • String (Unicode format, with double quotes, backslash is used as output sequence)
  • Boolean (true or false)
  • String (an ordered sequence of values, separated by commas and enclosed in square brackets; values do not have to be of the same type)
  • Object (an unordered collection of key:value pairs with the ‘:’ character separating the key and value, separated by commas and surrounded by curly braces. Keys must be low and distinct from other keys)
  • null (empty)

White spaces can be freely added between structural characters (brackets “{ } [ ]”, colons “:” and commas “,”).

JSON Structure

The structure can be organized as follows:

  • Collections of pairs (name / value)

    In various languages, this is realized as an object, record, structure, dictionary, hash table, keyed list, or associative array. This structure is marked with { } curly braces, and the name/value data is separated by
    comma.

    • Name is lower case double quotes.
    • Value
  • Array (ordered list of values)

    A string is marked with [ ] square brackets, and the members of the string are separated by a comma.

The following example shows a JSON representation of an object that describes a person. The object has first and last name fields represented by strings, a year number, an object representing the person’s address, and an array of phone number objects.

Code control and editing

The site http://jsonlint.com can be used for code control, which performs online code control. It is also good to use the site www.jsoneditoronline.org for easier editing of content in JSON format as well as minification of the code.

For good visibility of the code through the browser, it is possible to add add-ons for both Firefox and Chrome called “JSONView”. Pulling data from WordPress in JSON format is easy using the “JSON API” plugin which does the job pretty well even though it’s an old version that doesn’t get updated.

JavaScript and JSON

Since JSON syntax is a derivative of JavaScript object notation, it is very easy to work with JSON data in JavaScript.

Parsing

Parsing is creating a JavaScript object from JSON text data. Although a similar JSON object is not a JavaScript object! Differences between JSON structure (name/value) and code objectsJavaScript are:

  • Name in JSON structure can be any valid string including spaces while in JavaScript it is not allowed
  • The name in the JSON structure must be in double quotes while they are not used in JavaScript.

Therefore, it is necessary to transfer the JSON object to a JavaScript object, i.e. perform a parsing that will remove quotation marks and whitespace if present.

Example

We assign some JSON data to the variable:

We call a function that will parse the JSON text into a JavaScript object:

Now taking data from a Javascript object is simple and used to insert data into HTML:

Besides parse() there is an eval() function, but still the recommended way is to use JSON.parse for greater security. A correctly implemented JSONparser accepts only valid JSON, preventing potentially malicious code from being executed inadvertently.

JSON.stringify()

This function does the opposite of parsing, it turns a JavaScript object into valid JSON data.

Where are the function parameters:

  • value – Value to be passed to JSON string
  • replacer – (optional)
  • space – (optional) inserts white spaces into the JSON string for easier viewing. The number indicates the number of whites

Application example

JSON is very often used as an exchange between client and server. In this example, we will download a series of JSON objects from the file mojiLinkovi.txt with an ajax call. The source file with JSON is:

In the following code, an ajax request is sent to the server, which returns the data in JSON format, after which we parse and print it.

PHP and JSON

PHP support for JSON is in the form of two functions:

  • json_encode()
  • json_decode()

Both functions work with UTF-8 encoding.

json_encode()

This function takes an array and returns a string representation of the argument in JSON format, or false if an error occurred.

The parameters of the function are:

  • mixed $value is the data to be formatted in JSON format, it can be a plain string or a two-dimensional string encoded with UTF-8
  • $options is the principle that the function follows when formatting. If not specified, the default normal principle is used. Can be: JSON_HEX_QUOT, JSON_HEX_TAG, JSON_HEX_AMP, JSON_HEX_APOS, JSON_NUMERIC_CHECK, JSON_PRETTY_PRINT, JSON_UNESCAPED_SLASHES,
    JSON_FORCE_OBJECT, JSON_PRESERVE_ZERO_FRACTION, JSON_UNESCAPED_UNICODE, JSON_PARTIAL_OUTPUT_ON_ERROR
Example

The result of the function is:

Example

Returns

json_decode()

Based on the string representation of the argument in JSON format, this function forms the appropriate object/associative string or returns NULL in case of error.

The parameters of the function are:

  • json_string − encoded character string that must be UTF-8 encoded.
  • assoc – is a boolean value. When TRUE it returns a string, otherwise it returns an object
  • depth − an integer specifying the depth of the recursion
  • options − Integer type bitmask of JSON decode,JSON_BIGINT_AS_STRING is supported.
Example

this function returns an object:

Example

this function returns a string: