JSON (Data Sharing Format) with examples

json examples

JSON general information

JSON (JavaScript Object Notation) is one of the easier text open standards designed for legible data sharing. 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, so it has a shorter code that is easier to write and more readable. 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 types of data can be used within the JSON structure:

Number (Double-precision JavaScript comma-format, implementation-dependent)

String (Unicode format, with double quotes, backslash used as output sequence)

Boolean (true or false)

String (ordered sequence of values, separated by commas and framed by brackets; values need not be of the same type)

Object (unordered collection key: value of pairs with ‘:’ character separating key and value, separated by commas and framed by curly brackets. Keys must be low and different from other keys)

null (blank)

Whiteness can be freely added between structural characters (parentheses “{} []”, two dots “:” and commas “,”).

JSON Structure

The structure can be organized in the form of:

Pair collections (name / value)

In various languages, this is realized as an object, record, structure, vocabulary, hash table, key list, or associative array. This structure is marked with brackets and the name/value data is separated by a comma.

name is lowercase under double quotation marks.
value

Arrays (edited list of values)

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

The following example is a JSON representation of an object that describes a person. The object has the name and surname represented by a string, a year number, an object that displays that person’s address, and a number of objects with phone numbers.

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

Code control and editing

The code control site may be the http://jsonlint.com site, which performs online code control. It’s also a good idea to use www.jsoneditoronline.org to easily edit JSON content as well as code modification.

Add-ons can be added to both Firefox and Chrome under the name “JSONView” for good browser visibility. Pulling data from WordPress in JSON format is easy using the “JSON API” plugin which does a pretty good job even though it is an old version that is not 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.

Parse

Parsing is the creation of a JavaScript object from JSON text data. Although a similar JSON object is not a JavaScript object! The differences between the JSON structure (name/value) and JavaScript objects are:

The name of the JSON structure can be any valid string including whitespace, while JavaScript is not allowed

The name of the JSON structure must be in double quotation marks until JavaScript is used.

Therefore, it is necessary to move the JSON object to a JavaScript object, ie parse which will remove the quotation marks and whitespace if any.

Example

We assign the variable some JSON data:

var employees = '{"employees": [' +
'{"firstName": "John", "lastName": "doe"},' +
'{"firstName": "Anna", "lastName": "Smith"},' +
'{"firstName": "Peter", "lastName": "Jones"}]}';

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

var obj = JSON.parse (employee);

Now, extracting data from a Javascript object is easy and uses it to insert data into HTML:

<p id = "demo"> </p>
 
<Script>
   document.getElementById ("demo"). innerHTML =
   obj.employees [1] .firstName + "" + obj.employees [1] .lastName;
</ Script>

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

JSON.stringify ()

This function works opposite to parsing, making a valid JSON data from a Javascript object.

JSON.stringify(value[, replacer[, space]])

Where are the function parameters:

value – The value that is transferred to the JSON string
replacer – (optional)
space – (optional) inserts whitespace into the JSON string for easy viewing. The number indicates the whiteness number

Application example

JSON is often used as a drop-in for client-server exchanges. In this example, we will retrieve ajax from the myLinks.txt file by calling a series of JSON objects. The original JSON file is:

[
     {
       "display": "JavaScript Scripts",
       "url": "https://www.webprogramming.org"
     },
     {
       "display": "Youtube",
       "url": "https://www.youtube.com/"
     },
     {
       "display": "Udemy Courses",
       "url": "https://www.udemy.com/"
     }
]

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

// Function for printing data
function viewsLinks (arr) {
     var out = "";
     var i;
     for (i = 0; i <arr.length; i ++) {
         out + = '<a href="' + arr[i].url +'">' + arr [i] .display + '</a> <br>';
     }
     document.getElementById ("id01"). innerHTML = out;
}
 
// AJAX request
var xmlhttp = new XMLHttpRequest ();
var url = "myLinks.txt";
 
xmlhttp.onreadystatechange = function () {
     if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
        var myArr = JSON.parse (xmlhttp.responseText); // Parsing JSON data
        prikaziLinkove (myArr);
     }
}
 
xmlhttp.open ("GET", url, true);
xmlhttp.send ();

PHP and JSON

PHP support for JSON comes with two features:

json_encode ()
json_decode ()

Both functions work with UTF-8 encoding.

json_encode ()

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

json_encode(mixed $value, int $options = 0);

Function parameters are:

mixed $ value is data that needs to be formatted in JSON format, can be a plain string or a two-dimensional string encoded with UTF-8


$ options is a principle that the function adheres to when formatting. If not specified the default normal principle is used. May 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

<?php
$arr = array(&apos;a&apos; => 1, &apos;b&apos; => 2, &apos;c&apos; => 3, &apos;d&apos; => 4, &apos;e&apos; => 5);
echo json_encode($arr);
?> 

The result of the function is:

{"a":1,"b":2,"c":3,"d":4,"e":5}

Example

<?php
$arr = array(4 => "four", 8 => "eight");
echo json_encode($arr);
?> 

The result of the function is:

{"4":"four","8":"eight"}

json_decode()

This function, based on the argument representation string in JSON format, forms the corresponding object / associative string or returns NULL in case of error.

mixed json_decode ($json [,$assoc = false [, $depth = 512 [, $options = 0 ]]])

Function parameters are:

json_string – An encoded letter string that must be UTF-8 encoded.
assoc – is a boolean’s value. When TRUE returns an array, otherwise it returns an object
depth – an integer specifying the depth of recursion
options – An integer type bitmask of JSON decode, JSON_BIGINT_AS_STRING is supported.

Example

<?php
$string = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
var_dump (json_decode($string)); 

this function returns an object:

object(stdClass)#1 (5) {
    ["a"] => int(1)
    ["b"] => int(2)
    ["c"] => int(3)
    ["d"] => int(4)
    ["e"] => int(5)
}

Example

<?php
$string = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
var_dump (json_decode($string, true)); 

this function returns a string:

array(5) {
    ["a"] => int(1)
    ["b"] => int(2)
    ["c"] => int(3)
    ["d"] => int(4)
    ["e"] => int(5)
}
Likes:
15 0
Views:
1603
Article Categories:
PROGRAMMINGTECHNOLOGY

Leave a Reply

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