Difference between revisions of "JSON/ru"

From Free Pascal wiki
Jump to navigationJump to search
Line 59: Line 59:
 
== Правильный формат JSON ==
 
== Правильный формат JSON ==
  
There are a few rules and guidelines that define the JSON syntax (see RFC 4627):
+
Есть несколько правил и руководящих принципов, которые определяют синтаксис JSON (см RFC 4627):
  
* JSON objects are encapsulated within opening and closing brackets <code>{ }</code>. An empty object can be represented by <code>{ }</code>
+
* Объекты JSON включаются в открывающиеся и закрывающиеся скобки <code>{ }</code>. An empty object can be represented by <code>{ }</code>
 
* Arrays are encapsulated within opening and closing square brackets <code>[ ]</code>. An empty array can be represented by <code>[ ]</code>
 
* Arrays are encapsulated within opening and closing square brackets <code>[ ]</code>. An empty array can be represented by <code>[ ]</code>
 
* A member is represented by a key-value pair
 
* A member is represented by a key-value pair

Revision as of 10:50, 14 March 2016

English (en) suomi (fi) 日本語 (ja) 한국어 (ko) polski (pl) русский (ru) 中文(中国大陆)‎ (zh_CN)

Обзор

JSON(JavaScript Object Notation) является формой представления данных, которая обеспечивает стандартизированный формат обмена данными, используя простой текст. Как следует из названия, форма представления основана на подмножестве языка программирования JavaScript; тем не менее, эта форма полностью не зависит от языка. Помимо того, что легко человеку читать и писать, форма данных также легка для машининного для разбора и генерации.

Также, по сравнению с XML, более удобна для восприятия человеком.

Объекты JSON

Объекты JSON являются не более чем наборами пар имя/значение, разделенных запятыми (которые часто называются члены), заключенные в фигурные скобки:

{"name1":value1, "name2":value2 ...}

Для того, чтобы придать человеческий вид, для чтения и наглядности, пары имя/значение часто перечисляются в столбик:

{
	"name1": value1,
	"name2": value2
}

Название должно быть строкой в двойных кавычках, в то время как значение может быть любым из следующих:

  • простая строка, число, логическое значение или null (строки заключены в двойные кавычки):
{
    "id":1,
    "имя":"Валерий Шипков",
    "женат":false
}
  • массив, который представляет собой набор значений, разделенных запятыми в квадратных скобках:
{
    "простые_числа":[2, 3, 5, 7, 11, 13, 17],
    "нечётные_числа":[1,3,5,7]}
}
  • объект, который представляет собой набор (имя пара/значение), заключенное в фигурные скобки:
{
    "адрес":{"улица":"Аксакова", "город":"Калининград", "Страна":"Россия"}
}


Объекты JSON могут быть вложены произвольно для создания еще более сложных объектов:

{"user":
	{	"ползь_номер": 1900,
		"ползь_имя": "В.Шипков",
		"пароль": "12345",
		"группа": [ "admins", "users", "maintainers"]
	}
}

Правильный формат JSON

Есть несколько правил и руководящих принципов, которые определяют синтаксис JSON (см RFC 4627):

  • Объекты JSON включаются в открывающиеся и закрывающиеся скобки { }. An empty object can be represented by { }
  • Arrays are encapsulated within opening and closing square brackets [ ]. An empty array can be represented by [ ]
  • A member is represented by a key-value pair
  • The key of a member should be contained in double quotes
  • Each member SHOULD have a unique key within an object structure
  • The value of a member must be contained in double quotes if it is a string
  • Boolean values are represented using the true or false literals in lower case
  • Number values are represented using double-precision floating-point format; Scientific notation is supported; Numbers should not have leading zeroes
  • "Offensive" characters in a string need to be escaped using the backslash character
  • Null values are represented by the null literal in lower case
  • Other object types, such as dates, are not natively supported and should be converted to strings; to be managed by the parser/client
  • Each member of an object or each array value must be followed by a comma if it is not the last one
  • The common extension for json files is .json
  • The MIME type for json files is application/json

Implementations

JSON implementation is not very strict, and a lot of leeway is granted to the client application and/or parser to enforce the guidelines. As usual when writing code:

  • be liberal in what you accept
  • be strict (adhering to the standard) in what you send.

There are two main implementations of JSON:

The official JSON Specification syntax

This implementation adheres strictly to the RFC 4627 guidelines above and does not allow deviation from the specification.

The Javascript syntax

This implementation follows the implementation of the Javascript programming language and as such allows for a few deviations from the official specification. For example:

  1. allows un-quoted keys eg {name: "John Doe" }
  2. allows single quotes for keys and/or string values; and a liberal mix of single and double quotes eg {'name': "John Doe", "language":'Pascal'}
  3. allows trailing comma after the last member of an array and/or object eg {"keywords":["if","begin","for",], "IDEs":["Lazarus","fpIDE","MSEide"],}

See also