Skip to content

Commit 168a0d5

Browse files
committed
ok
1 parent 0831ea2 commit 168a0d5

File tree

9 files changed

+245
-19
lines changed

9 files changed

+245
-19
lines changed
File renamed without changes.
File renamed without changes.

archive/5-json/2-serialize-object-circular/solution.md renamed to 1-js/3-object-basics/9-json/2-serialize-object-circular/solution.md

File renamed without changes.

archive/5-json/2-serialize-object-circular/task.md renamed to 1-js/3-object-basics/9-json/2-serialize-object-circular/task.md

File renamed without changes.
Lines changed: 142 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,33 +1,159 @@
1-
# JSON methods, toJSON
1+
# JSON methods, toJSON [todo: after Date]
22

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.
44

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.
66

77
Javascript provides built-in methods to convert objects into JSON and back, which also allow a few tricks that make them even more useful.
88

99
[cut]
1010

11-
## Формат JSON
11+
## JSON.stringify
1212

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.
1414

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`,
2171
- `null`.
2272

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+
24151

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.
26153

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).
29155

30-
## Метод JSON.parse
156+
## JSON.parse
31157

32158
Вызов `JSON.parse(str)` превратит строку с данными в формате JSON в JavaScript-объект/массив/значение.
33159

1-js/4-more-syntax/3-advanced-loops/article.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -136,7 +136,9 @@ alert(`Length: ${arr.length}`); // 5, remember, length is the last index + 1
136136
137137
````
138138

139+
## Summary [todo]
139140

141+
Futher in the chapter <info:map-set-weakmap-weakset> we will meet other data structures `Map` and `Set` that also implement methods `keys()`, `values()` and `entries()`.
140142

141143

142144

1-js/5-code-quality/index.md

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
1-
# TODO: Code quality
1+
# Code quality
2+
3+
This chapter goes early to explain coding practices that we'll use further in the development.
24

3-
In this chapter we cover common, but very important things. Probably you'll want to reread some chapters later when you learn more about the language and write more code.
45

1-js/plan2.txt

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,8 @@ data-types
4242
number (rounding, precision, isFinite, isNaN, parse*, Math.*)
4343
string (quotes, search, substring, tagged template notice)
4444

45-
<<< object-descriptors
45+
46+
<<< property-descriptors
4647

4748
array-methods (TODO: translate tasks)
4849
map-set-weakmap-weakset

1-js/plan3.txt

Lines changed: 96 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,96 @@
1+
getting-started
2+
introduction
3+
editor
4+
devtools
5+
first-steps
6+
hello-world (intro, ext scripts)
7+
structure
8+
use strict
9+
variables (const, name things right)
10+
types (no objects, but typeof)
11+
type-conversions (conversions string/number/boolean, no objects)
12+
operators
13+
comparison (no objects)
14+
uibasic
15+
logical-ops
16+
while-for (labels, no objects)
17+
switch
18+
function-basics (decl, shadowing, naming, default params)
19+
function-expressions-arrows (function expr, arrow, todo: move new Function out of this?)
20+
javascript-specials (TODO, remove it? migrate all function* to separate chapter?)
21+
object-basics
22+
object(props, for-in, refs, assign)
23+
garbage-collection
24+
object-methods (this, method syntax, no call/apply)
25+
primitives-methods (on-the-fly objects)
26+
symbol
27+
object-toprimitive
28+
array
29+
iterable
30+
<<< json
31+
more-syntax
32+
function-arguments-rest-spread
33+
destructuring-assignment (also func params destructuring)
34+
advanced-loops (iterators over objects, arrays)
35+
code-quality
36+
debugging-chrome (TODO)
37+
coding-style (TODO)
38+
write-unmaintainable-code (TODO)
39+
test-driven-development (TODO)
40+
polyfills (TODO)
41+
data-types
42+
number (rounding, precision, isFinite, isNaN, parse*, Math.*)
43+
string (quotes, search, substring, tagged template notice)
44+
45+
46+
<<< property-descriptors
47+
48+
array-methods (TODO: translate tasks)
49+
map-set-weakmap-weakset
50+
date (TODO: tasks)
51+
deeper
52+
recursion
53+
running execution context = where + lexical environment = envrec + outer
54+
context stack
55+
pow task
56+
traverse list task
57+
task: traverse list back
58+
closures
59+
LE outer
60+
returning a function
61+
garbage collection
62+
var
63+
window
64+
function-object
65+
name property (obj props, methods, assignments - set it)
66+
length property
67+
custom properties
68+
new function
69+
scheduling: settimeout, setinterval
70+
recursive settimeout
71+
call-apply-decorators
72+
bind
73+
74+
-------
75+
76+
<<< descriptors (TODO: LATER, need JSON to output, better after inheritance to explain getOwnProps)
77+
<<< getter setter
78+
79+
80+
constructors
81+
classes
82+
instanceof
83+
84+
после 4-object сделать
85+
descriptors
86+
87+
88+
89+
more-features
90+
try..catch
91+
setTimeout
92+
JSON
93+
94+
95+
======
96+
class A extends Object != class A

0 commit comments

Comments
 (0)