Skip to content

Instantly share code, notes, and snippets.

@sunmeat
Created April 18, 2025 13:03
Show Gist options
  • Save sunmeat/048927434b7507ee8791103c50728b05 to your computer and use it in GitHub Desktop.
Save sunmeat/048927434b7507ee8791103c50728b05 to your computer and use it in GitHub Desktop.
сериализация массива объектов javascript
<!DOCTYPE html>
<html lang="">
<head>
<meta charset="UTF-8">
<title>Сериализация массива объектов</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;
}
h1 {
text-align: center;
}
</style>
</head>
<body>
<h1>О создателях JSON и XML: Дуглас Крокфорд и Тим Брей</h1>
<pre id="output"></pre>
<script>
class Person {
constructor(data) {
this.id = data.id;
this.name = data.name;
this.birth = data.birth;
this.citizenship = data.citizenship;
this.education = data.education;
this.profession = data.profession;
this.knownFor = data.knownFor;
this.currentStatus = data.currentStatus;
this.website = data.website;
this.contributions = data.contributions;
this.interests = data.interests;
this.favoriteQuote = data.favoriteQuote;
this.active = data.active;
}
toJSON() {
return {
id: this.id,
name: this.name,
birth: `Родился тут: ${this.birth.place} in ${this.birth.year}`,
citizenship: this.citizenship,
education: this.education,
profession: this.profession,
knownFor: this.knownFor,
website: this.website,
contributions: this.contributions,
interests: this.interests,
favoriteQuote: this.favoriteQuote,
active: this.active
};
}
}
const people = [
new Person({
id: 1,
name: "Дуглас Крокфорд",
birth: {year: 1955, place: "Миннесота, США"},
citizenship: "США",
education: {
university: "Университет штата Калифорния в Сан-Франциско",
graduationYear: 1975
},
profession: "программист",
knownFor: "создание и популяризация JSON",
currentStatus: "жив, пишет, рассказывает, наблюдает за деградацией фронтенда",
website: "https://crockford.com",
contributions: {
JSON: {
origin: "придуман как альтернатива XML",
published: "json.org (2002)",
rfc: "RFC 4627 (июль 2006)"
},
ELanguage: "участие в разработке языка E"
},
interests: [
"структура данных",
"чистый код",
"минимализм в синтаксисе",
"публичные лекции"
],
favoriteQuote: "I didn’t invent JSON. I just discovered it lying in plain sight.",
active: true
}),
new Person({
id: 2,
name: "Тим Брей",
birth: {year: 1955, place: "Ванкувер, Канада"},
citizenship: "Канада",
education: {
university: "Университет Гуэлфа",
graduationYear: 1976
},
profession: "инженер-программист",
knownFor: "соавтор спецификации XML",
currentStatus: "активно пишет блог, занимается open-source",
website: "https://www.tbray.org",
contributions: {
XML: {
origin: "разработан для структурированных данных",
published: "W3C Recommendation (1998)",
role: "соредактор спецификации"
},
Web: "участие в стандартах W3C"
},
interests: [
"веб-технологии",
"открытые стандарты",
"блоггинг",
"фотография"
],
favoriteQuote: "The Web is the most wildly successful distributed system ever.",
active: true
})
];
try {
// сериализация массива people с replacer
const jsonString = JSON.stringify(people, null, 2);
document.getElementById("output").textContent = jsonString;
const parsedPeople = JSON.parse(jsonString, null);
console.log("Распарсенный объект:", parsedPeople);
const invalidJson = '{name: "Дуглас Крокфорд"}';
JSON.parse(invalidJson);
} catch (error) {
console.error("Ошибка парсинга:", error.message);
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment