Lesson 20 / الدرس 20

JSON and saving data / JSON وحفظ البيانات

Text that looks like a JavaScript object but is not one. It is how data crosses between a server and a page, and how a page keeps something between visits — and it loses a few things on the way, quietly.

نص يشبه كائن جافاسكربت وليس كذلك. وهو كيف تعبر البيانات بين خادم وصفحة، وكيف تحتفظ صفحة بشيء بين الزيارات — ويفقد أشياء قليلة في الطريق بهدوء.

Object out, text in

JSON.stringify(value)          object -> text
JSON.stringify(value, null, 2)  the same, indented and readable
JSON.parse(text)               text -> object, or throws

localStorage.setItem('cart', JSON.stringify(cart));
const cart = JSON.parse(localStorage.getItem('cart') ?? '[]');

storage holds STRINGS only. everything else must be stringified.
The two functions are exact opposites, and almost everything you will do with JSON is one of them. The demonstration runs a value out and back, and then shows what does not survive the trip.

What JSON is not

In JavaScriptIn JSON
{ name: 'Sara' }{"name": "Sara"} — double quotes on both
undefinedNot allowed — the key disappears entirely
A functionNot allowed — silently dropped
new Date()A string; parse gives you back a string
A trailing commaA syntax error
// a commentNot allowed anywhere

The fourth row causes real bugs. A date goes out as text and comes back as text, so back.placed.getFullYear() fails with "not a function" on data that looked perfectly fine. If you need a real date after parsing, build one: new Date(back.placed).

Three practical notes. JSON.stringify(value, null, 2) is what you want when a human will read the output — the two is the indent. localStorage survives the browser closing and sessionStorage does not, which is the only difference between them. And storage keys are shared across your whole origin, so prefix yours with something specific — shop.cart rather than cart — or two features on the same site will quietly overwrite each other.

Try it live / جرّب بنفسك

Preview / المعاينة

Check yourself / اختبر نفسك

1. What happens to a Date through stringify and parse?

2. Why wrap JSON.parse of stored data in a try?

3. What must never go into localStorage?

Your task / مهمتك

Build an object holding at least six different kinds of value — including undefined, a function and a date — send it out with JSON.stringify(value, null, 2), bring it back, and print a line per key saying whether it survived and as what. Then feed JSON.parse three pieces of broken text and record each message. On your own page, add a note field that saves on every keystroke and is still there after a reload, with the load wrapped in try and a sensible fallback.

ابنِ كائنًا يحمل ستة أنواع قيم مختلفة على الأقل — منها undefined ودالة وتاريخ — وأخرجه بـJSON.stringify(value, null, 2)، وأعِده، واطبع سطرًا لكل مفتاح يقول هل نجا وبأي صورة. ثم أطعِم JSON.parse ثلاث قطع نص معطوب وسجّل كل رسالة. وعلى صفحتك أنت، أضف حقل ملاحظة يُحفظ عند كل ضغطة مفتاح ويبقى بعد إعادة التحميل، والتحميل مغلَّف بـtry وبديل معقول.

  • Six kinds of value, each reported after the round trip ستة أنواع قيم كل منها مُبلَّغ عنه بعد الرحلة
  • Three parse failures with their messages ثلاثة إخفاقات تحليل برسائلها
  • A note that survives a reload ملاحظة تنجو من إعادة التحميل
  • The load wrapped in try with a fallback التحميل مغلَّف بـtry ببديل
How do you want to submit? / كيف تريد التسليم؟