Skip to content

Instantly share code, notes, and snippets.

@sunmeat
Created April 18, 2025 12:47
Show Gist options
  • Save sunmeat/277472a3b8b99331940e2fa9833a4221 to your computer and use it in GitHub Desktop.
Save sunmeat/277472a3b8b99331940e2fa9833a4221 to your computer and use it in GitHub Desktop.
toJSON example
<!DOCTYPE html>
<html lang="">
<head>
<meta charset="UTF-8">
<title>Дуглас Крокфорд — создатель JSON</title>
<style>
body {
font-family: monospace;
background-color: #111;
color: #0ff;
padding: 2rem;
}
pre {
background-color: #222;
padding: 1rem;
border-radius: 8px;
overflow-x: auto;
}
</style>
</head>
<body>
<h1>О создателе JSON — Дугласе Крокфорде</h1>
<pre id="output"></pre>
<script>
class Crockford {
constructor() {
this.name = "Дуглас Крокфорд";
this.birth = {
year: 1955,
place: "Миннесота, США"
};
this.citizenship = "США";
this.education = {
university: "Университет штата Калифорния в Сан-Франциско",
graduationYear: 1975
};
this.profession = "программист";
this.knownFor = "создание и популяризация JSON";
this.currentStatus = "жив, пишет, рассказывает, наблюдает за деградацией фронтенда";
this.website = "https://crockford.com";
this.appearance = "на мероприятии 'Browser Wars: Episode II Attack of the DOMs', 28 февраля 2007";
this.toolsCreated = ["JSLint", "JSMin", "ADsafe", "JSON.parse", "JSON.stringify"];
this.books = [
"JavaScript: The Good Parts",
"How JavaScript Works"
];
this.earlyCareer = {
1980: "купил Atari 8-bit, написал игру Galahad and the Holy Grail для APX",
then: [
"работал в Atari",
"перешёл в National Semiconductor после её продажи",
"в 1984 году устроился в Lucasfilm, затем в Paramount Pictures"
]
};
this.startups = [
{
name: "Electric Communities",
role: "сооснователь и CEO (1994–1995)",
with: ["Рэнди Фармер", "Чип Морнингстар"]
},
{
name: "State Software (Veil Networks)",
role: "технический директор (2001–2002)"
}
];
this.contributions = {
JSON: {
origin: "придуман как альтернатива XML",
published: "json.org (2002)",
rfc: "RFC 4627 (июль 2006)"
},
ELanguage: "участие в разработке языка E"
};
this.interests = [
"структура данных",
"чистый код",
"минимализм в синтаксисе",
"публичные лекции",
"разоблачение 'плохих частей' языка"
];
this.favoriteQuote = "I didn’t invent JSON. I just discovered it lying in plain sight.";
this.personality = {
style: "прямолинейный, ироничный, технически строгий",
stateOfMind: "устал от небрежности программистов"
};
}
toJSON() {
return {
name: this.name,
birth: `Born in ${this.birth.place} in ${this.birth.year}`,
citizenship: this.citizenship,
education: this.education,
profession: this.profession,
knownFor: this.knownFor,
website: this.website,
toolsCreated: this.toolsCreated,
books: this.books,
earlyCareer: this.earlyCareer,
startups: this.startups,
contributions: this.contributions,
interests: this.interests,
favoriteQuote: this.favoriteQuote,
personality: this.personality
};
}
}
const crockford = new Crockford();
// const formattedJson = JSON.stringify(crockford, null, 2); // toJSON вызывается автоматически
const jsonObject = crockford.toJSON(); // [object Object] !!!
const formattedJson = JSON.stringify(jsonObject, null, 2);
document.getElementById("output").textContent = formattedJson;
//////////////////////////////////////////////////////////////////////////////////////
const user = {
name: "Alex",
age: 36,
toJSON() {
return {customName: this.name}; // сериализуем только имя в другом формате
}
};
console.log(JSON.stringify(user)); // '{"customName":"Alex"}'
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment