[Go to site: main page, start]

0% found this document useful (0 votes)
3 views20 pages

JavaScript Draft - JSON

JSON (JavaScript Object Notation) is a text-based data format used for representing structured data, primarily in web applications. It supports various data types such as objects, arrays, strings, numbers, booleans, and null, and is easily readable and editable by humans. JavaScript provides built-in methods like JSON.stringify() and JSON.parse() for converting between JSON strings and JavaScript objects.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views20 pages

JavaScript Draft - JSON

JSON (JavaScript Object Notation) is a text-based data format used for representing structured data, primarily in web applications. It supports various data types such as objects, arrays, strings, numbers, booleans, and null, and is easily readable and editable by humans. JavaScript provides built-in methods like JSON.stringify() and JSON.parse() for converting between JSON strings and JavaScript objects.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

JSON (JavaScript Object Notation) - Working with JSON - JSON - what is JSON?

​ 1
Data types​ 2
Description​ 3
JavaScript and JSON differences​ 3
Any JSON text is a valid JavaScript expression...​ 3
Full JSON syntax​ 3
Nesting objects​ 4
JSON structure​ 5
Arrays as JSON​ 6
Other notes​ 7
Encoding and decoding JSON in JavaScript - JSON methods, toJSON - Static
methods​ 7
[Link](value[, replacer[, space]]) - [Link]​ 8
Excluding and transforming: replacer​ 11
Formatting: space​ 13
Custom “toJSON()”​ 14
[Link](text[, reviver]) - [Link]​ 15
Using reviver​ 17
Object literal notation vs JSON​ 18
Online tools for working with JSON​ 19
JSON Schema​ 19
Summary​ 19
Tasks​ 19
Turn the object into JSON and back​ 19
Exclude backreferences​ 20

JSON (JavaScript Object Notation) - Working


with JSON - JSON - what is JSON?
The JSON object contains methods for parsing JavaScript Object Notation (JSON) and
converting values to JSON. It can't be called or constructed, and aside from its two
method properties, it has no interesting functionality of its own.

JavaScript Object Notation (JSON) is a standard text-based data format for representing
structured data based on JavaScript object syntax. It is commonly used for transmitting
data in web applications (e.g., sending some data from the server to the client, so it can be
displayed on a web page, or vice versa).
JSON is a great format to store data, widely used in JavaScript but not only
JSON is a file format that’s used to store and interchange data.
Data is stored in a set of key-value pairs.
This data is human readable, which makes JSON perfect for manual editing.

Here’s an example of a JSON string:


{
"name": "Flavio",
"age": 35
}
From this little snippet you can see that keys are wrapped in double quotes, a colon separates
the key and the value, and the value can be of different types.

Key-value sets are separated by a comma.


Spacing (spaces, tabs, new lines) does not matter in a JSON file. The above is equivalent to
{"name": "Flavio","age": 35}
or
{"name":
"Flavio","age":
35}
but as always well-formatted data is better to understand.

JSON was born in 2002 and got hugely popular thanks to its ease of use, and flexibility, and
although being born out of the JavaScript world, it quickly spread out to other programming
languages.
It’s defined in the ECMA-404 standard.
JSON strings are commonly stored in .json files and transmitted over the network with an
application/json MIME type.

JSON is a text-based data format following JavaScript object syntax, which was
popularized by Douglas Crockford. Even though it closely resembles JavaScript object
literal syntax, it can be used independently from JavaScript, and many programming
environments feature the ability to read (parse) and generate JSON.
JSON exists as a string — useful when you want to transmit data across a network. It needs
to be converted to a native JavaScript object when you want to access the data.
This is not a big issue — JavaScript provides a global JSON object that has methods
available for converting between the two.
Note: Converting a string to a native object is called deserialization, while converting a
native object to a string so it can be transmitted across the network is called serialization.
A JSON string can be stored in its own file, which is basically just a text file with an
extension of .json, and a MIME type of application/json.

Data types
JSON supports some basic data types:
●​ Number: any number that’s not wrapped in quotes
●​ String: any set of characters wrapped in quotes
●​ Boolean: true or false
●​ Array: a list of values, wrapped in square brackets
●​ Object: a set of key-value pairs, wrapped in curly brackets
●​ null: the null word, which represents an empty value
Any other data type must be serialized to a string (and then de-serialized) in order to be stored
in JSON.

Description
JavaScript and JSON differences
JSON is a syntax for serializing objects, arrays, numbers, strings, booleans, and null. It is
based upon JavaScript syntax but is distinct from it: some JavaScript is not JSON.

Objects and Arrays


Property names must be double-quoted strings; trailing commas are forbidden.

Numbers
Leading zeros are prohibited. A decimal point must be followed by at least one digit.
NaN and Infinity are unsupported.

Any JSON text is a valid JavaScript expression...


...But only in JavaScript engines that have implemented the proposal to make all JSON
text valid ECMA-262. In engines that haven't implemented the proposal, U+2028 LINE
SEPARATOR and U+2029 PARAGRAPH SEPARATOR are allowed in string literals and
property keys in JSON; but their use in these features in JavaScript string literals is a
SyntaxError.
Consider this example where [Link]() parses the string as JSON and eval executes
the string as JavaScript:
let code = '"\u2028\u2029"'
[Link](code) // evaluates to "\u2028\u2029" in all engines
eval(code) // throws a SyntaxError in old engines

Other differences include allowing only double-quoted strings and having no provisions for
undefined or comments. For those who wish to use a more human-friendly configuration
format based on JSON, there is JSON5, used by the Babel compiler, and the more
commonly used YAML.

Full JSON syntax


The full JSON syntax is as follows:
JSON = null
or true or false
or JSONNumber
or JSONString
or JSONObject
or JSONArray

JSONNumber = - PositiveNumber
or PositiveNumber
PositiveNumber = DecimalNumber
or DecimalNumber . Digits
or DecimalNumber . Digits ExponentPart
or DecimalNumber ExponentPart
DecimalNumber = 0
or OneToNine Digits
ExponentPart = e Exponent
or E Exponent
Exponent = Digits
or + Digits
or - Digits
Digits = Digit
or Digits Digit
Digit = 0 through 9
through 9

JSONString = ""
or " StringCharacters "
StringCharacters = StringCharacter
or StringCharacters StringCharacter
StringCharacter = any character
except " or \ or U+0000 through U+001F
or EscapeSequence
EscapeSequence = \" or \/ or \\ or \b or \f or \n or \r or \t
or \u HexDigit HexDigit HexDigit HexDigit
HexDigit = 0 through 9
or A through F
or a through f

JSONObject = { }
or { Members }
Members = JSONString : JSON
or Members , JSONString : JSON

JSONArray = [ ]
or [ ArrayElements ]
ArrayElements = JSON
or ArrayElements , JSON

Insignificant whitespace may be present anywhere except within a JSONNumber (numbers


must contain no whitespace) or JSONString (where it is interpreted as the corresponding
character in the string, or would cause an error). The tab character (U+0009), carriage
return (U+000D), line feed (U+000A), and space (U+0020) characters are the only valid
whitespace characters.

Nesting objects
You can organize data in a JSON file using a nested object:
{
"name": {
"firstName": "Flavio",
"lastName": "Copes"
},
"age": 35,
"dogs": [
{ "name": "Roger" },
{ "name": "Syd" }
],
"country": {
"details": {
"name": "Italy"
}
}
}

JSON structure
As described above, JSON is a string whose format very much resembles JavaScript object
literal format. You can include the same basic data types inside JSON as you can in a
standard JavaScript object — strings, numbers, arrays, booleans, and other object
literals. This allows you to construct a data hierarchy, like so:
'{
"squadName": "Super hero squad",
"homeTown": "Metro City",
"formed": 2016,
"secretBase": "Super tower",
"active": true,
"members": [
{
"name": "Molecule Man",
"age": 29,
"secretIdentity": "Dan Jukes",
"powers": [
"Radiation resistance",
"Turning tiny",
"Radiation blast"
]
},
{
"name": "Madame Uppercut",
"age": 39,
"secretIdentity": "Jane Wilson",
"powers": [
"Million tonne punch",
"Damage resistance",
"Superhuman reflexes"
]
},
{
"name": "Eternal Flame",
"age": 1000000,
"secretIdentity": "Unknown",
"powers": [
"Immortality",
"Heat Immunity",
"Inferno",
"Teleportation",
"Interdimensional travel"
]
}
]
}'
If we loaded this string into a JavaScript program, parsed it into a variable called
superHeroes for example, we could then access the data inside it using the same
dot/bracket notation we looked at in the JavaScript object basics article. For example:
[Link]
superHeroes['active']
To access data further down the hierarchy, you have to chain the required property names
and array indexes together. For example, to access the third superpower of the second
hero listed in the members list, you'd do this:
superHeroes['members'][1]['powers'][2]
1.​ First we have the variable name — superHeroes.
2.​ Inside that we want to access the members property, so we use ["members"].
3.​ members contains an array populated by objects. We want to access the second
object inside the array, so we use [1].
4.​ Inside this object, we want to access the powers property, so we use ["powers"].
5.​ Inside the powers property is an array containing the selected hero's superpowers.
We want the third one, so we use [2].
Note: We've made the JSON seen above available inside a variable in our [Link]
example (see the source code). Try loading this up and then accessing data inside the variable
via your browser's JavaScript console.

Arrays as JSON
Above we mentioned that JSON text basically looks like a JavaScript object inside a string.
We can also convert arrays to/from JSON. Below is also valid JSON, for example:
'[
{
"name": "Molecule Man",
"age": 29,
"secretIdentity": "Dan Jukes",
"powers": [
"Radiation resistance",
"Turning tiny",
"Radiation blast"
]
},
{
"name": "Madame Uppercut",
"age": 39,
"secretIdentity": "Jane Wilson",
"powers": [
"Million tonne punch",
"Damage resistance",
"Superhuman reflexes"
]
}
]'
The above is perfectly valid JSON. You'd just have to access array items (in its parsed
version) by starting with an array index, for example [0]["powers"][0].

Other notes
●​ JSON is purely a string with a specified data format — it contains only properties,
no methods.
●​ JSON requires double quotes to be used around strings and property names.
Single quotes are not valid other than surrounding the entire JSON string.
●​ Even a single misplaced comma or colon can cause a JSON file to go wrong, and
not work. You should be careful to validate any data you are attempting to use
(although computer-generated JSON is less likely to include errors, as long as the
generator program is working correctly). You can validate JSON using an
application like JSONLint.
●​ JSON can actually take the form of any data type that is valid for inclusion inside
JSON, not just arrays or objects. So for example, a single string or number would be
valid JSON.
●​ Unlike in JavaScript code in which object properties may be unquoted, in JSON only
quoted strings may be used as properties.

Encoding and decoding JSON in JavaScript - JSON


methods, toJSON - Static methods
ECMAScript 5 in 2009 introduced the JSON object in the JavaScript standard, which among
other things offers the [Link]() and [Link]() methods.
Before it can be used in a JavaScript program, a JSON in string format must be parsed and
transformed in data that JavaScript can use.

Let’s say we have a complex object, and we’d like to convert it into a string, to send it over a
network, or just to output it for logging purposes.
Naturally, such a string should include all important properties.
We could implement the conversion like this:
let user = {
name: "John",
age: 30,
toString() {
return `{name: "${[Link]}", age: ${[Link]}}`;
}
};
alert(user); // {name: "John", age: 30}
…But in the process of development, new properties are added, old properties are renamed and
removed. Updating such toString every time can become a pain. We could try to loop over
properties in it, but what if the object is complex and has nested objects in properties? We’d
need to implement their conversion as well.
Luckily, there’s no need to write the code to handle all this. The task has been solved already.

[Link](value[, replacer[, space]]) - [Link]


[Link]() takes a JavaScript object as its parameter, and returns a string that
represents it in JSON:

Return a JSON string corresponding to the specified value, optionally including only
certain properties or replacing property values in a user-defined manner. By default, all
instances of undefined are replaced with null, and other unsupported native data
types are censored. The replacer option allows for specifying other behavior.

The JSON (JavaScript Object Notation) is a general format to represent values and objects. It is
described as in RFC 4627 standard. Initially it was made for JavaScript, but many other
languages have libraries to handle it as well. 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.
JavaScript provides methods:
●​ [Link] to convert objects into JSON.
●​ [Link] to convert JSON back into an object.
For instance, here we [Link] a student:
let student = {
name: 'John',
age: 30,
isAdmin: false,
courses: ['html', 'css', 'js'],
wife: null
};
let json = [Link](student);
alert(typeof json); // we've got a string!
alert(json);
/* JSON-encoded object:
{
"name": "John",
"age": 30,
"isAdmin": false,
"courses": ["html", "css", "js"],
"wife": null
}
*/
The method [Link](student) takes the object and converts it into a string.
The resulting json string is called a JSON-encoded or serialized or stringified or marshalled
object. We are ready to send it over the wire or put into a plain data store.
Please note that a JSON-encoded object has several important differences from the object
literal:
●​ Strings use double quotes. No single quotes or backticks in JSON. So 'John' becomes
"John".
●​ Object property names are double-quoted also. That’s obligatory. So age:30 becomes
"age":30.

[Link] can be applied to primitives as well.

JSON supports following data types:


●​ Objects { ... }
●​ Arrays [ ... ]
●​ Primitives:
●​ strings,
●​ numbers,
●​ boolean values true/false,
●​ null.

For instance:
// a number in JSON is just a number
alert( [Link](1) ) // 1
// a string in JSON is still a string, but double-quoted
alert( [Link]('test') ) // "test"
alert( [Link](true) ); // true
alert( [Link]([1, 2, 3]) ); // [1,2,3]

JSON is data-only language-independent specification, so some JavaScript-specific object


properties are skipped by [Link].
Namely:
●​ Function properties (methods).
●​ Symbolic keys and values.
●​ Properties that store undefined.
let user = {
sayHi() { // ignored
alert("Hello");
},
[Symbol("id")]: 123, // ignored
something: undefined // ignored
};
alert( [Link](user) ); // {} (empty object)

Usually that’s fine. If that’s not what we want, then soon we’ll see how to customize the process.
The great thing is that nested objects are supported and converted automatically.
For instance:
let meetup = {
title: "Conference",
room: {
number: 23,
participants: ["john", "ann"]
}
};
alert( [Link](meetup) );
/* The whole structure is stringified:
{
"title":"Conference",
"room":{"number":23,"participants":["john","ann"]},
}
*/

The important limitation: there must be no circular references.


For instance:
let room = {
number: 23
};
let meetup = {
title: "Conference",
participants: ["john", "ann"]
};
[Link] = room; // meetup references room
[Link] = meetup; // room references meetup
[Link](meetup); // Error: Converting circular structure to JSON
Here, the conversion fails, because of circular reference: [Link] references meetup,
and [Link] references room:

Excluding and transforming: replacer


The full syntax of [Link] is:
let json = [Link](value[, replacer, space])

value
A value to encode.

replacer
Array of properties to encode or a mapping function function(key, value).

space
Amount of space to use for formatting

Most of the time, [Link] is used with the first argument only. But if we need to
fine-tune the replacement process, like to filter out circular references, we can use the second
argument of [Link].
If we pass an array of properties to it, only these properties will be encoded.
For instance:
let room = {
number: 23
};
let meetup = {
title: "Conference",
participants: [{name: "John"}, {name: "Alice"}],
place: room // meetup references room
};
[Link] = meetup; // room references meetup
alert( [Link](meetup, ['title', 'participants']) );
// {"title":"Conference","participants":[{},{}]}
Here we are probably too strict. The property list is applied to the whole object structure. So the
objects in participants are empty, because name is not in the list.
Let’s include in the list every property except [Link] that would cause the circular
reference:
let room = {
number: 23
};
let meetup = {
title: "Conference",
participants: [{name: "John"}, {name: "Alice"}],
place: room // meetup references room
};
[Link] = meetup; // room references meetup
alert( [Link](meetup, ['title', 'participants', 'place', 'name',
'number']) );
/*
{
"title":"Conference",
"participants":[{"name":"John"},{"name":"Alice"}],
"place":{"number":23}
}
*/
Now everything except occupiedBy is serialized.
But the list of properties is quite long.
Fortunately, we can use a function instead of an array as the replacer.
The function will be called for every (key, value) pair and should return the “replaced” value,
which will be used instead of the original one. Or undefined if the value is to be skipped.
In our case, we can return value “as is” for everything except occupiedBy. To ignore
occupiedBy, the code below returns undefined:
let room = {
number: 23
};
let meetup = {
title: "Conference",
participants: [{name: "John"}, {name: "Alice"}],
place: room // meetup references room
};
[Link] = meetup; // room references meetup
alert( [Link](meetup, function replacer(key, value) {
alert(`${key}: ${value}`);
return (key == 'occupiedBy') ? undefined : value;
}));
/* key:value pairs that come to replacer:
: [object Object]
title: Conference
participants: [object Object],[object Object]
0: [object Object]
name: John
1: [object Object]
name: Alice
place: [object Object]
number: 23
occupiedBy: [object Object]
*/
Please note that replacer function gets every key/value pair including nested objects and
array items. It is applied recursively. The value of this inside replacer is the object that
contains the current property.
The first call is special. It is made using a special “wrapper object”: {"": meetup}. In other
words, the first (key, value) pair has an empty key, and the value is the target object as a
whole. That’s why the first line is ":[object Object]" in the example above.
The idea is to provide as much power for replacer as possible: it has a chance to analyze and
replace/skip even the whole object if necessary.

Formatting: space
The third argument of [Link](value, replacer, space) is the number of spaces
to use for pretty formatting.
Previously, all stringified objects had no indents and extra spaces. That’s fine if we want to
send an object over a network. The space argument is used exclusively for a nice output.
Here space = 2 tells JavaScript to show nested objects on multiple lines, with indentation of 2
spaces inside an object:
let user = {
name: "John",
age: 25,
roles: {
isAdmin: false,
isEditor: true
}
};
alert([Link](user, null, 2));
/* two-space indents:
{
"name": "John",
"age": 25,
"roles": {
"isAdmin": false,
"isEditor": true
}
}
*/
/* for [Link](user, null, 4) the result would be more indented:
{
"name": "John",
"age": 25,
"roles": {
"isAdmin": false,
"isEditor": true
}
}
*/
The third argument can also be a string. In this case, the string is used for indentation instead
of a number of spaces.
The space parameter is used solely for logging and nice-output purposes.
Custom “toJSON()”
Like toString for string conversion, an object may provide method toJSON for to-JSON
conversion. [Link] automatically calls it if available.
For instance:
let room = {
number: 23
};
let meetup = {
title: "Conference",
date: new Date([Link](2017, 0, 1)),
room
};
alert( [Link](meetup) );
/*
{
"title":"Conference",
"date":"2017-01-01T00:00:00.000Z", // (1)
"room": {"number":23} // (2)
}
*/
Here we can see that date (1) became a string. That’s because all dates have a built-in toJSON
method which returns such kind of string.
Now let’s add a custom toJSON for our object room (2):
let room = {
number: 23,
toJSON() {
return [Link];
}
};
let meetup = {
title: "Conference",
room
};
alert( [Link](room) ); // 23
alert( [Link](meetup) );
/*
{
"title":"Conference",
"room": 23
}
*/
As we can see, toJSON is used both for the direct call [Link](room) and when room
is nested in another encoded object.

[Link](text[, reviver]) - [Link]


[Link]() takes a JSON string as its parameter, and returns an object that contains the
parsed JSON:
Parse the string text as JSON, optionally transform the produced value and its
properties, and return the value. Any violations of the JSON syntax, including those
pertaining to the differences between JavaScript and JSON, cause a SyntaxError to be
thrown. The reviver option allows for interpreting what the replacer has used to
stand in for other datatypes.

To decode a JSON-string, we need another method named [Link].


The syntax:
let value = [Link](str, [reviver]);

str
JSON-string to parse.

reviver
Optional function(key,value) that will be called for each (key, value) pair and can transform
the value.
For instance:
// stringified array
let numbers = "[0, 1, 2, 3]";
numbers = [Link](numbers);
alert( numbers[1] ); // 1
Or for nested objects:
let userData = '{ "name": "John", "age": 35, "isAdmin": false, "friends":
[0,1,2,3] }';
let user = [Link](userData);
alert( [Link][1] ); // 1

The JSON may be as complex as necessary, objects and arrays can include other objects and
arrays. But they must obey the same JSON format.
Here are typical mistakes in hand-written JSON (sometimes we have to write it for debugging
purposes):
let json = `{
name: "John", // mistake: property name without quotes
"surname": 'Smith', // mistake: single quotes in value (must
be double)
'isAdmin': false // mistake: single quotes in key (must be
double)
"birthday": new Date(2000, 2, 3), // mistake: no "new" is allowed, only
bare values
"friends": [0,1,2,3] // here all fine
}`;
Besides, JSON does not support comments. Adding a comment to JSON makes it invalid.
There’s another format named JSON5, which allows unquoted keys, comments, etc. But this is
a standalone library, not in the specification of the language.

The regular JSON is that strict not because its developers are lazy, but to allow easy, reliable
and very fast implementations of the parsing algorithm.

Using reviver
[Link]() can also accepts an optional second argument, called the reviver function.
You can use that to hook into the parsing and perform any custom operation:
[Link](string, (key, value) => {
if (key === 'name') {
return `Name: ${value}`
} else {
return value
}
})

Imagine, we got a stringified meetup object from the server.


It looks like this:
// title: (meetup title), date: (meetup date)
let str = '{"title":"Conference","date":"2017-11-30T12:00:00.000Z"}';
…And now we need to deserialize it, to turn back into JavaScript object.
Let’s do it by calling [Link]:
let str = '{"title":"Conference","date":"2017-11-30T12:00:00.000Z"}';
let meetup = [Link](str);
alert( [Link]() ); // Error!
Whoops! An error!
The value of [Link] is a string, not a Date object. How could [Link] know that it
should transform that string into a Date?
Let’s pass to [Link] the reviving function as the second argument, that returns all values
“as is”, but date will become a Date:
let str = '{"title":"Conference","date":"2017-11-30T12:00:00.000Z"}';
let meetup = [Link](str, function(key, value) {
if (key == 'date') return new Date(value);
return value;
});
alert( [Link]() ); // now works!

By the way, that works for nested objects as well:


let schedule = `{
"meetups": [
{"title":"Conference","date":"2017-11-30T12:00:00.000Z"},
{"title":"Birthday","date":"2017-04-18T12:00:00.000Z"}
]
}`;
schedule = [Link](schedule, function(key, value) {
if (key == 'date') return new Date(value);
return value;
});
alert( [Link][1].[Link]() ); // works!

Object literal notation vs JSON


The object literal notation is not the same as the JavaScript Object Notation (JSON).
Although they look similar, there are differences between them:
●​ JSON permits only property definition using "property": value syntax. The
property name must be double-quoted, and the definition cannot be a shorthand.
●​ In JSON the values can only be strings, numbers, arrays, true, false, null, or
another (JSON) object.
●​ A function value (see "Methods" below) can not be assigned to a value in JSON.
●​ Objects like Date will be a string after [Link]().
●​ [Link]() will reject computed property names and an error will be thrown.

Online tools for working with JSON


There are many useful tools you can use.
One of them is JSONLint, the JSON Validator. Using it you can verify if a JSON string is
valid.
JSONFormatter is a nice tool to format a JSON string so it’s more readable according to
your conventions.
JSON Schema
While JSON is very flexible right from the start, there are times when you need a bit more rigid
organization to keep things in place.
This is when JSON Schema gets into play. It’s a way to annotate and validate JSON documents
according to some specific format you create.

Examples - Example JSON


{
"browsers": {
"firefox": {
"name": "Firefox",
"pref_url": "about:config",
"releases": {
"1": {
"release_date": "2004-11-09",
"status": "retired",
"engine": "Gecko",
"engine_version": "1.7"
}
}
}
}
}

Summary
●​ JSON is a data format that has its own independent standard and libraries for most
programming languages.
●​ JSON supports plain objects, arrays, strings, numbers, booleans, and null.
●​ JavaScript provides methods [Link] to serialize into JSON and [Link] to
read from JSON.
●​ Both methods support transformer functions for smart reading/writing.
●​ If an object has toJSON, then it is called by [Link].

Tasks
Turn the object into JSON and back
importance: 5
Turn the user into JSON and then read it back into another variable.
let user = {
name: "John Smith",
age: 35
};
solution
let user = {
name: "John Smith",
age: 35
};
let user2 = [Link]([Link](user));

Exclude backreferences
importance: 5
In simple cases of circular references, we can exclude an offending property from serialization
by its name.
But sometimes we can’t just use the name, as it may be used both in circular references and
normal properties. So we can check the property by its value.
Write replacer function to stringify everything, but remove properties that reference meetup:
let room = {
number: 23
};

let meetup = {
title: "Conference",
occupiedBy: [{name: "John"}, {name: "Alice"}],
place: room
};

// circular references
[Link] = meetup;
[Link] = meetup;

alert( [Link](meetup, function replacer(key, value) {


/* your code */
}));

/* result should be:


{
"title":"Conference",
"occupiedBy":[{"name":"John"},{"name":"Alice"}],
"place":{"number":23}
}
*/
solution
let room = {
number: 23
};

let meetup = {
title: "Conference",
occupiedBy: [{name: "John"}, {name: "Alice"}],
place: room
};

[Link] = meetup;
[Link] = meetup;

alert( [Link](meetup, function replacer(key, value) {


return (key != "" && value == meetup) ? undefined : value;
}));

/*
{
"title":"Conference",
"occupiedBy":[{"name":"John"},{"name":"Alice"}],
"place":{"number":23}
}
*/
Here we also need to test key=="" to exclude the first call where it is normal that value is
meetup.

You might also like