Sie sind auf Seite 1von 12

JSON (JavaScript Object Notation)

JSON Data Interchange Format


All complex data that is communicated over an HTTP connection must be serialized into
a string representation that can be transmitted over the web. JSON is a text-based,
lightweight, and human-readable format for data exchange between clients and servers
in web applications. Consider the following block diagram of the simple client-server
architecture. Assume that the client is a browser that sends an HTTP request to the
server, and the server serves the request and responses as expected. This is visualized
as:

In the preceding two-way communication, the data format used is a serialized string,
with the combination of key-value pairs enveloped in parentheses.

Since JSON is used to transmit serialized data over the internet, we will need to make a
note of its MIME type. The MIME type for JSON data is application/json. If MIME
type headers are not sent across the browser, it treats the incoming JSON as plain text.
Understanding JSON Syntax

As the JSON structure is based on the JavaScript object literal syntax, they share a
number of similarities.
These are the core elements of JSON syntax:

 Data is presented in key/value pairs.

 Data elements are separated by commas.

 Curly brackets {} determine objects.

 Square brackets [] designate arrays.

As a result, JSON object literal syntax looks like this:

{“key”:“value”,“key”:“value”,“key”:“value”.}

JSON Datatypes

String

Number
Primitive
Boolean

Data Types Null

Object
Structure
Array

Array
An array is an ordered collection of values. An array value can contain JSON objects,
meaning that it uses the same key/value pair concept. For example:
{
"students":[
{"firstName":"Tom", "lastName":"Jackson"},
{"firstName":"Linda", "lastName":"Garner"},
{"firstName":"Adam", "lastName":"Cooper"}
]
}
The information within the square brackets forms an array of three objects.
Object
JSON objects are made up of pairs of two components:

 Keys are strings – sequences of characters surrounded by quotation marks.

 Values are valid JSON data types. They can be in the form of an array, object,
string, boolean, number, or null.

A colon is placed between each key and value, with a comma separating pairs. Both
components are held in quotation marks.
{
"employees":{
"firstName":"Tom",
"lastName":"Jackson"
}
}

String
String values are set sequences of zero or more Unicode characters with double
quotes enclosing them.
{"firstName":"Tom"}
{"firstName":"Tom"}
{"firstName":"Tom"}
This example shows that Tom signifies a string as it’s a set of characters inside a
double quote.

Number
A number in JSON should be an integer or a floating point.
For example:
{“age”:30}

Boolean
Booleans contain true or false as values.
{“married”:false)

Null
Null is an empty value. It’s to show that there is no information.
{"bloodType":null}
Ways to Store JSON Data

There are two ways to store JSON data – objects and arrays. The former are sets of
key/value pairs, while the latter are lists of values.

Using Objects

A JSON object starts and ends with curly brackets. It contains key/value pairs called
properties, with commas separating each line. A colon goes between each key and
value.
While keys must be strings, values can be either of the six JSON data types – strings,
numbers, objects, arrays, booleans, or nulls.
Note that JSON objects are different from objects in the JSON data type. The former
serve as a method of storing data while the latter represent an associative array of
key/value pairs.
Let’s look at an example where we have three key/value pairs. firstName,
lastName, and gender are the keys, and Tom, Jackson, and male are the values.
The JSON object will look like this:
{
"firstName":"Tom",
"lastName":"Jackson",
"gender":"male"
}

The values used are strings, therefore, they are also inside quotation marks, just like
the keys.

Using Arrays

Another way to store data involves using arrays. The values are enclosed in square
brackets, with commas separating each line. Each value in JSON arrays can be of a
different type.

{ "firstName":"Tom", "lastName":”Jackson”, “gender”:”male”, "hobby":[ “football",


"reading", "swimming" ] }
What differentiates this from the previous method is the fourth key/value
pair. hobby is the key, and there are several values (football, reading, swimming) in
the square brackets representing an array.

Here is a simple example of JSON usage


{
"className":"Class 4C",
"year":2023,
"phoneNumber":null,
"active":true,
"homeroomTeacher":{"firstName":"Shobha", "lastName":"Nair"},
"members":[{
"firstName":"Evan","lastName":"Mathew"},
{"firstName":"Gautam","lastName":"Renjith"},
{"firstName":"Juan","lastName":"Francis"},
]}

Here’s what each pair indicates:

 The first line “className”:”Class 4C” is a string.


 The second pair “year”:2023 has a numeric value.
 The third pair “phoneNumber”:null represents a null – there is no value.
 The fourth pair “active”:true is a boolean expression.
 The fifth line “homeroomTeacher”:{“firstName”:”Shobha”,
“lastName”:”Nair”} represents an object literal.
 Lastly, the script from the sixth line onwards is an array.

JSON as JavaScript Object

JSON provides different methods that help to convert the JS object to a string or
provides parsing of a JSON string, which is written in a JSON format to a JavaScript
object. For this, JSON.parse() & JSON.stringify methods are used.
JSON.stringify() Method is used to convert JavaScript objects into JSON strings. This
method only takes a single argument, and that argument is an object to be converted
into JSON strings. It works oppositely to JSON.parse() method. JSON.stringify can take
replacer parameters as a function, we can write logic on key-value pairs of objects.
While receiving data from a web server, data has to be in the string format, & after
parsing data with JSON.parse(), the data become an Object.

The format of the Date is not allowed in JSON, So you can include the Date in the
string.

Example: This example describes the basic usage of JSON.stringify() Method.

const myInfo = {
Name: "GFG",
Age:22,
Department : "Computer Science and Engineering",
Year: "3rd"
}
const Obj = JSON.stringify(myInfo);
console.log(Obj)

Explanation: Here, the variable myInfo contains a JavaScript Object with 4


Properties: Name, Age, Department, and Year. The JSON.stringify() method returns
the JSON string, which is stored inside the object Obj.
Output:
{"Name":"GFG","Age":22,"Department":"Computer Science and
Engineering","Year":"3rd"}

JSON.parse() Method is used to convert a JSON string into a JavaScript Object.


JavaScript objects are basically storage that store some data of that respective class. It
takes a single argument, which is the JSON string to be parsed. Note that the string to
be parsed must be in backticks ‘ ’ and all the words must be in double cots. When
sending data to a web server, The data has to be in string format. It can be used to
store the data in the local storage of the browser because the browser store data in
local storage in key-value pairs.
Example: This example describes the basic usage of JSON.parse() Method.
Javascript

const myInfo = `{
"Name": "GFG",
"Age":22,
"Department" : "Computer Science and Engineering",
"Year": "3rd"
}`

const Obj = JSON.parse(myInfo);


console.log(Obj.Name)
console.log(Obj.Age)

Explanation: Here, the myInfo variable stored a JSON string in form of an object with
the two properties Name, age, Department, and Year. We have used JSON.parse() to
parse the string and converted it into a whole new object. The variable obj stored that
parsed object and we can access the properties of those objects using the dot operator.
Output:
GFG
22

Manipulating JSON data with PHP


PHP has some built-in functions to handle JSON.
JSON Functions
 json_encode - Returns the JSON representation of a value.
 json_decode - Decodes a JSON string.
 json_last_error - Returns the last error occurred.
Encoding JSON in PHP - json_encode
PHP json_encode function is used for encoding JSON in PHP. This function returns the
JSON representation of a value on success or FALSE on failure.
Syntax
string json_encode ( $value [, $options = 0 ] )
Parameters
 value − The value being encoded. This function only works with UTF-8 encoded
data.
 options − This optional value is a bitmask consisting of JSON_HEX_QUOT,
JSON_HEX_TAG, JSON_HEX_AMP, JSON_HEX_APOS, JSON_NUMERIC_CHECK,
JSON_PRETTY_PRINT, JSON_UNESCAPED_SLASHES, JSON_FORCE_OBJECT.
Example
The following example shows how to convert an array into JSON with PHP −
<?php
$arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);
echo json_encode($arr);
?>

While executing, this will produce the following result −


{"a":1,"b":2,"c":3,"d":4,"e":5}
The following example shows how the PHP objects can be converted into JSON −
<?php
class Emp {
public $name = "";
public $hobbies = "";
public $birthdate = "";
}
$e = new Emp();
$e->name = "sachin";
$e->hobbies = "sports";
$e->birthdate = date('m/d/Y h:i:s a', "8/5/1974 12:20:03 p");
$e->birthdate = date('m/d/Y h:i:s a', strtotime("8/5/1974 12:20:03"));
echo json_encode($e);
?>

While executing, this will produce the following result −


{"name":"sachin","hobbies":"sports","birthdate":"08\/05\/1974 12:20:03 pm"}
Decoding JSON in PHP – json_decode
PHP json_decode function is used for decoding JSON in PHP. This function returns the
value decoded from json to appropriate PHP type.
Syntax
mixed json_decode ($json [,$assoc = false [, $depth = 512 [, $options = 0 ]]])
Paramaters
 json_string − It is an encoded string which must be UTF-8 encoded data.
 assoc − It is a boolean type parameter, when set to TRUE, returned objects will
be converted into associative arrays.
 depth − It is an integer type parameter which specifies recursion depth
 options − It is an integer type bitmask of JSON decode, JSON_BIGINT_AS_STRING
is supported.
Example
The following example shows how PHP can be used to decode JSON objects −
<?php
$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
var_dump(json_decode($json));
var_dump(json_decode($json, true));
?>

While executing, it will produce the following result −


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

JSON Schema
(https://json-schema.org/learn/miscellaneous-
examples#miscellaneous-examples)
1. Basic schema
This example provides a typical minimum you are likely to see in JSON Schema. It
contains:
 $id keyword
 $schema keyword
 title annotation keyword
 type instance data model
 properties validation keyword
 Three keys: firstName, lastName and age each with their own:
o description annotation keyword.
o type instance data model
 minimum validation keyword on the age key.
schema
{
"$id": "https://example.com/person.schema.json",
"$schema": "https://json-schema.org/draft/2020-12/schema",
"title": "Person",
"type": "object",
"properties": {
"firstName": {
"type": "string",
"description": "The person's first name."
},
"lastName": {
"type": "string",
"description": "The person's last name."
},
"age": {
"description": "Age in years which must be equal to or greater than zero.",
"type": "integer",
"minimum": 0
}
}
}

Data
{
"firstName": "John",
"lastName": "Doe",
"age": 21
}

In the data example, we provide values for the firstName, lastName, and age properties.
The values match the defined schema, where firstName is a string, lastName is a string,
and age is an integer greater than or equal to zero.

2. Arrays of things
Arrays are fundamental structures in JSON -- here we demonstrate a couple of ways
they can be described:
 An array of string values.
 An array of objects.
We also introduce the following with this example:
 $defs keyword
 $ref keyword
For the fruits property:
type is set to "array" to indicate it's an array.
items describes the items within the array. In this case, they should be of type "string".

For the vegetables property:


type is also set to "array" to indicate it's an array.
items references the $defs/veggie definition, indicating that the items in the array should
conform to the "veggie" schema defined in the $defs section.
Schema
{
"$id": "https://example.com/arrays.schema.json",
"$schema": "https://json-schema.org/draft/2020-12/schema",
"description": "A representation of a person, company, organization, or place",
"type": "object",
"properties": {
"fruits": {
"type": "array",
"items": {
"type": "string"
}
},
"vegetables": {
"type": "array",
"items": { "$ref": "#/$defs/veggie" }
}
},
"$defs": {
"veggie": {
"type": "object",
"required": [ "veggieName", "veggieLike" ],
"properties": {
"veggieName": {
"type": "string",
"description": "The name of the vegetable."
},
"veggieLike": {
"type": "boolean",
"description": "Do I like this vegetable?"
}
}
}
}
}

Data
{
"fruits": [ "apple", "orange", "pear" ],
"vegetables": [
{
"veggieName": "potato",
"veggieLike": true
},
{
"veggieName": "broccoli",
"veggieLike": false
}
]
}
The data example shows the usage of arrays. The fruits property contains an array of
strings, while the vegetables property contains an array of objects, each adhering to the
"veggie" schema definition.
3. Regular expression pattern
This example introduces the pattern keyword and defines an object with a property
called code that must match a specific regular expression pattern: ^[A-Z]{3}-\d{3}$. The
pattern here requires three uppercase letters followed by a hyphen and three digits.
Schema
{
"$id": "https://example.com/regex-pattern.schema.json",
"$schema": "https://json-schema.org/draft/2020-12/schema",
"title": "Regular Expression Pattern",
"type": "object",
"properties": {
"code": {
"type": "string",
"pattern": "^[A-Z]{3}-\\d{3}$"
}
}
}

Data
{
"code": "ABC-123"
}
The provided data, "ABC-123", satisfies this pattern defined in the schema.

Das könnte Ihnen auch gefallen