|
1 | | -# JSON methods, toJSON |
| 1 | +# JSON methods, toJSON [todo: after Date] |
2 | 2 |
|
3 | | -The [JSON](http://en.wikipedia.org/wiki/JSON) is mostly used to represent an object as a string. |
| 3 | +The [JSON](http://en.wikipedia.org/wiki/JSON) (JavaScript Object Notation) format is used to represent an object as a string. |
4 | 4 |
|
5 | | -When we need to send an object over a network -- from the client to server or backwards, this format is used almost all the time. |
| 5 | +When we need to send an object over a network -- from the client to server or in the reverse direction, this format is the most widespread. |
6 | 6 |
|
7 | 7 | Javascript provides built-in methods to convert objects into JSON and back, which also allow a few tricks that make them even more useful. |
8 | 8 |
|
9 | 9 | [cut] |
10 | 10 |
|
11 | | -## Формат JSON |
| 11 | +## JSON.stringify |
12 | 12 |
|
13 | | -Данные в формате JSON ([RFC 4627](http://tools.ietf.org/html/rfc4627)) представляют собой: |
| 13 | +JSON, despite its name (JavaScript Object Notation) is an independent standard. It is described as [RFC 4627](http://tools.ietf.org/html/rfc4627). Most programming languages have libraries to encode objects in it. So it's easy to use JSON for data exchange when the client uses Javascript and the server is written on Ruby/PHP/Java/Whatever. |
14 | 14 |
|
15 | | -- JavaScript-объекты `{ ... }` или |
16 | | -- Массивы `[ ... ]` или |
17 | | -- Значения одного из типов: |
18 | | - - строки в двойных кавычках, |
19 | | - - число, |
20 | | - - логическое значение `true`/`false`, |
| 15 | +In Javascript, the native method [JSON.stringify(value)](mdn:js/JSON/stringify) accepts a value and returns it's representation as a string in JSON format. |
| 16 | + |
| 17 | +For instance: |
| 18 | +```js run |
| 19 | +let student = { |
| 20 | + name: 'John', |
| 21 | + age: 30, |
| 22 | + isAdmin: false, |
| 23 | + courses: ['html', 'css', 'js'], |
| 24 | + wife: null |
| 25 | +}; |
| 26 | + |
| 27 | +let json = JSON.stringify(student); |
| 28 | + |
| 29 | +alert(typeof json); // string |
| 30 | +alert(json); |
| 31 | +/* |
| 32 | +{ |
| 33 | + "name": "John", |
| 34 | + "age": 30, |
| 35 | + "isAdmin": false, |
| 36 | + "courses": ["html", "css", "js"], |
| 37 | + "wife": null |
| 38 | +} |
| 39 | +*/ |
| 40 | +``` |
| 41 | + |
| 42 | +The JSON-encoded object has several important differences from the original variant: |
| 43 | + |
| 44 | +- Strings use double quotes. No single quotes or backticks in JSON. So `'John'` became `"John"`. |
| 45 | +- Object property names are double-quoted also. Also obligatory. So `name` became `"name"`. |
| 46 | + |
| 47 | +`JSON.stringify` can be applied not only to objects, but to other values: |
| 48 | + |
| 49 | +```js run |
| 50 | +// a number in JSON is just a number |
| 51 | +alert( JSON.stringify(1) ) // 1 |
| 52 | + |
| 53 | +// a string in JSON is still a string, but double-quoted |
| 54 | +alert( JSON.stringify('test') ) // "test" |
| 55 | + |
| 56 | +// double quotes are escaped |
| 57 | +alert( JSON.stringify('"quoted"') ) // "\"quoted\"" (inner quotes are escaped with \") |
| 58 | + |
| 59 | +// array of objects |
| 60 | +alert( JSON.stringify([{name: "John"},{name: "Ann"}]) ); // [{"name":"John"},{"name":"Ann"}] |
| 61 | +``` |
| 62 | + |
| 63 | +The supported JSON types are: |
| 64 | + |
| 65 | +- Objects `{ ... }` |
| 66 | +- Arrays `[ ... ]` |
| 67 | +- Primitives: |
| 68 | + - strings, |
| 69 | + - numbers, |
| 70 | + - boolean values `true/false`, |
21 | 71 | - `null`. |
22 | 72 |
|
23 | | -Почти все языки программирования имеют библиотеки для преобразования объектов в формат JSON. |
| 73 | +In the examples above we can see them all. |
| 74 | + |
| 75 | +JSON format does not support any other values. |
| 76 | + |
| 77 | +For instance, functions and `undefined` values, symbolic properties are skipped by `JSON.stringify`: |
| 78 | + |
| 79 | +```js run |
| 80 | +let user = { |
| 81 | + sayHi() { // ignored |
| 82 | + alert("Hello"); |
| 83 | + }, |
| 84 | + [Symbol("id")]: 123, // ignored |
| 85 | + something: undefined // ignored |
| 86 | +}; |
| 87 | + |
| 88 | +alert( JSON.stringify(user) ); // {} (empty object) |
| 89 | +``` |
| 90 | + |
| 91 | +### Custom "toJSON" |
| 92 | + |
| 93 | +Normally, an object is represented with a list of its properties. |
| 94 | + |
| 95 | +But it may provide its own JSON-transformation by implementing method `toJSON`. |
| 96 | + |
| 97 | +For instance: |
| 98 | + |
| 99 | +```js run |
| 100 | +let room = { |
| 101 | + number: 23 |
| 102 | +}; |
| 103 | + |
| 104 | +event = { |
| 105 | + title: "Conference", |
| 106 | + date: new Date(Date.UTC(2017, 0, 1)), |
| 107 | + room |
| 108 | +}; |
| 109 | + |
| 110 | +alert( JSON.stringify(event) ); |
| 111 | +/* |
| 112 | + { |
| 113 | + "title":"Conference", |
| 114 | +*!* |
| 115 | + "date":"2017-01-01T00:00:00.000Z", // (1) |
| 116 | +*/!* |
| 117 | + "room": {"number":23} // (2) |
| 118 | + } |
| 119 | +*/ |
| 120 | +``` |
| 121 | + |
| 122 | +Please note that `date` `(1)` became a string. That's because all dates have a built-in `toJSON` method. |
| 123 | + |
| 124 | + |
| 125 | +Обратим внимание на два момента: |
| 126 | + |
| 127 | +1. Дата превратилась в строку. Это не случайно: у всех дат есть встроенный метод `toJSON`. Его результат в данном случае -- строка в таймзоне UTC. |
| 128 | +2. У объекта `room` нет метода `toJSON`. Поэтому он сериализуется перечислением свойств. |
| 129 | + |
| 130 | + Мы, конечно, могли бы добавить такой метод, тогда в итог попал бы его результат: |
| 131 | + |
| 132 | + ```js run |
| 133 | + var room = { |
| 134 | + number: 23, |
| 135 | + *!* |
| 136 | + toJSON: function() { |
| 137 | + return this.number; |
| 138 | + } |
| 139 | + */!* |
| 140 | + }; |
| 141 | + |
| 142 | + alert( JSON.stringify(room) ); // 23 |
| 143 | + ``` |
| 144 | + |
| 145 | + |
| 146 | + |
| 147 | + |
| 148 | + |
| 149 | +If our object wants to provide its own logic for JSON conversion TOJSON |
| 150 | + |
24 | 151 |
|
25 | | -Основные методы для работы с JSON в JavaScript -- это: |
| 152 | +The result of `JSON.stringify` is a string. We can send it over the wire or put in the plain data storage. |
26 | 153 |
|
27 | | -- `JSON.parse` -- читает объекты из строки в формате JSON. |
28 | | -- `JSON.stringify` -- превращает объекты в строку в формате JSON, используется, когда нужно из JavaScript передать данные по сети. |
| 154 | +To turn a JSON-string back into the object, we need another method named [JSON.parse](mdn:js/JSON/parse). |
29 | 155 |
|
30 | | -## Метод JSON.parse |
| 156 | +## JSON.parse |
31 | 157 |
|
32 | 158 | Вызов `JSON.parse(str)` превратит строку с данными в формате JSON в JavaScript-объект/массив/значение. |
33 | 159 |
|
|
0 commit comments