דוגמת JSON Stringify - כיצד לנתח אובייקט JSON עם JS

יש כל כך הרבה שפות תכנות, ולכל שפה יש את התכונות שלה. אך לכולם משותף אחד: הם מעבדים נתונים. ממחשבון פשוט ועד מחשבי-על, כולם עובדים על נתונים.

כך גם אצל בני אדם: יש כל כך הרבה מדינות, כל כך הרבה תרבויות וכל כך הרבה ידע בכל קהילה.

אך כדי לתקשר עם קהילות אחרות, אנשים זקוקים למדיום משותף. שפה היא לבני אדם מה JSON לתכנות, מדיום משותף להעברת נתונים.

מה זה JSON?

JSON מייצג J AVA S cript O bject N otation. אז לפני שנבין את JSON בואו נבין אובייקטים ב- JavaScript.

בכל שפת תכנות יש שיטה כלשהי לאחסון נתונים דומים יחד. ב- C, למשל, הם נקראים מבנים.

ב- JavaScript אובייקטים הם אוסף של זוגות ערכי מפתח, כאשר הערכים יכולים להיות כל משתנה (מספר, מחרוזת, בוליאני), אובייקט אחר, או אפילו פונקציה. אובייקטים שימושיים מאוד בתכנות מונחה עצמים.

תכנות מונחה עצמים הוא פרדיגמת תכנות המבוססת על המושג "אובייקטים", שיכול להכיל נתונים, בצורת שדות וקוד, בצורת פרוצדורות.

בואו נסתכל על דוגמא.

ב- JavaScript, אובייקטים מוגדרים באמצעות סוגריים מתולתלים, למשל:

var obj = {};

הנה, objיש אובייקט ריק. ניתן גם ליצור אובייקטים באמצעות קונסטרוקטורים, למשל:

function Student(name, roll_number, age) { this.name = name; this.roll_number = roll_number; this.age = age; } var student1 = new Student("Abhishek", "123", 18); console.log(student1.name, student1.roll_number, student1.age);

זה ייתן את התפוקה Abhishek 123 18.

כך אתה יוצר אובייקטים ב- JavaScript. אך אובייקטים אלה הם עדיין משתנים הספציפיים רק ל- JavaScript.

אם ברצונך לייצא את האובייקטים האלה, ולשלוח אותם למשל לשרת, אתה זקוק לשיטה לקידודם. בואו נראה איך זה נעשה.

JSON Stringify

על מנת להעביר נתונים ממכשיר אחד לשני, ושפה אחת לאחרת, אנו זקוקים למוסכמה מובנית, אחידה ומוגדרת היטב.

למרות JSON מבוסס על אובייקטים JS, תנאים מסוימים צריכים להיות תקפים. למרבה המזל, אתה לא צריך להיות מודאג מהתנאים האלה - כי ב- JavaScript יש לנו שיטה שנקראת JSON.stringify().

שיטה זו משמשת להמרת אובייקט JS למחרוזת מקודדת אשר ניתן להעביר לכל מקום מבלי לאבד נתונים.

זה אולי נראה קסום שכל קידוד יכול להיות מקודד למחרוזת ולשלוח אותו לכל מקום. בואו נבין את זה יותר לעומק באמצעות כמה דוגמאות.

זהו אב-הטיפוס של שיטת החמרה:

JSON.stringify(value[, replacer[, space]])

הפרמטר הראשון הוא valueשהוא האובייקט שברצונך להדק. הפרמטר השני והשלישי הם אופציונליים, וניתן להשתמש בהם אם ברצונך להתאים אישית את אופן קידודו (למשל, המפריד והכניסה).

בואו ננסה להחמיר את הדוגמה שלנו לעיל.

function Student(name, roll_number, age) { this.name = name; this.roll_number = roll_number; this.age = age; } var student1 = new Student("Abhishek", "123", 18); var str = JSON.stringify(student1); console.log(str);

זה ייתן את התפוקה {"name":"Abhishek","roll_number":"123","age":18}.

אם אנו משתמשים בפרמטרים אופציונלי, כלומר נחליף JSON.stringify(student1)עם JSON.stringify(student1, null, 2), נקבל משהו כזה:

{ "name": "Abhishek", "roll_number": "123", "age": 18 }

אתה יכול להשתמש בהם כדי להדפיס JSON בפורמט קריא. בואו ננסה דוגמה נוספת.

כאן נשתמש בשיטות אובייקט. שיטות אובייקט הן פונקציות בתוך אובייקט שאפשר לקרוא לו עם אותו אובייקט, תוך שימוש בשיטות שבדוגמה שלנו לעיל:

function Student(name, roll_number, age) { this.name = name; this.roll_number = roll_number; this.age = age; this.print = function() { console.log(this.name, this.roll_number, this.age); } } var student1 = new Student("Abhishek", "123", 18); student1.print();

זה ייתן את אותה תפוקה כמו הדוגמה הראשונה, כלומר Abhishek 123 18.

ניתן להשתמש בשיטות אובייקט לביצוע פונקציות המשויכות לאובייקט ולהשתמש בתכונות האובייקט. בואו ננסה להדק את האובייקט הזה.

function Student(name, roll_number, age) { this.name = name; this.roll_number = roll_number; this.age = age; this.print = function() { console.log(this.name, this.roll_number, this.age); } } var student1 = new Student("Abhishek", "123", 18); var str = JSON.stringify(student1); console.log(str);

זה עדיין ייתן לך את אותה תפוקה {"name":"Abhishek","roll_number":"123","age":18},.

לפיכך, מתעלמים משיטות האובייקט על ידי פונקציית החומרה. אם אתה רוצה שגם הם ישודרו, עליך להמיר אותם תחילה למחרוזת.

לדוגמה, אתה יכול להתקשר student1.print = student1.print.toString()ואז להחמיר. ואז היית מקבל משהו כזה:

{"name":"Abhishek","roll_number":"123","age":18,"print":"function() {\n    console.log(this.name, this.roll_number, this.age);\n  }"}

בואו ניקח בחשבון אובייקט אחר:

var obj = {}; obj.key1 = "value1"; obj.key2 = obj; var str = JSON.stringify(obj); console.log(obj);

זה יזרוק שגיאה באמירה Uncaught TypeError: Converting circular structure to JSON.

This happens because key2 is referencing back to obj. Such objects are known as circular objects, and they cannot be converted to a JSON string.

This is where the second parameter comes in handy. Although I won't demonstrate how it works here, you can find the solution on this MDN page.

This is how you encode JSON. Now let's see how to parse a JSON string.

JSON parse

Just how JavaScript has a function to stringify JSON, we also have a function to parse that stringified JSON. This is the function prototype:

JSON.parse(text[, reviver])

Here, the first parameter is the JSON string which needs to be parsed. The second parameter is optional, and can be a function to modify the parsed JSON before returning. Let's demonstrate this method using an example.

function Student(name, roll_number, age) { this.name = name; this.roll_number = roll_number; this.age = age; } var student1 = new Student("Abhishek", "123", 18); var str = JSON.stringify(student1); var parsedJSON = JSON.parse(str); console.log(parsedJSON,name. parsedJSON.roll_number, parsedJSON.age);

And the output will be Abhishek 123 18, so the JSON string was successfully parsed.

You could use this to send data from client to server. The data to be sent can be JSON encoded at the client and the stringified JSON will be parsed at the server and processed. This makes it really easy.

JSON can also be used to transmit data across different programs written in different languages. All languages have libraries to stringify and parse JSON.

JSON vs. XML

XML or eXtensible Markup Language is a very popular way of storing and transmitting data, similar to JSON. It existed before JSON and is still widely used today.

For example, it's used in RSS feeds, which are still the most popular way of subscribing to some publication or author. There are also XML sitemaps which are a list of all pages on a website. And search engines use them to see if there are any new pages to be crawled.

XML uses markup format – similar to HTML but much stricter.

JSON and XML have various similarities and differences, as explained in the following points:

  • Both are human-readable
  • Both have a hierarchial structure
  • Both are widely supported across various programming languages
  • Both can be fetched from the server using HTTP requests
  • JSON is shorter than XML
  • JSON can use arrays
  • JSON can be parsed using standard JavaScript functions, whereas XML needs to be parsed using the XML DOM (which is slower)

The same data can be expressed in JSON and XML as follows:

JSON:

{"employees":[ { "firstName":"Quincy", "lastName":"Larson" }, { "firstName":"Abigail", "lastName":"Rennemeyer" }, { "firstName":"Abhishek", "lastName":"Chaudhary" } ]}

XML:

  Quincy Larson   Abigail Rennemeyer   Abhishek Chaudhary  

JSON טוב יותר מ- XML ​​מסיבות רבות, אך אין זה אומר שעלינו לזנוח את ה- XML. ובכל זאת, JSON יהפוך לצורה המועדפת להעברת נתונים בעתיד.

JWT - העתיד של JSON

JSON Web Token (JWT) הוא תקן פתוח המגדיר דרך קומפקטית ועצמאית להעברה מאובטחת של מידע בין הצדדים כאובייקט JSON.

ניתן לאמת ולסמוך על מידע זה מכיוון שהוא חתום דיגיטלית. ניתן לחתום על JWT באמצעות סוד (עם אלגוריתם HMAC) או צמד מפתחות ציבורי / פרטי באמצעות RSA או ECDSA.

באמצעות אסימונים אלה ניתן לחתום על נתוני JSON ולאמת את זהות השולח. מאז שנחתם הנתונים, אם טופלו בנתונים כלשהם תדעו זאת מיד.

Though we won't discuss the implementation in full here, we can understand how it works. A JSON Web Token consists of three parts, the header, the payload and the signature.

The header consists of the type of token and algorithm used, the payload consists of the data, and the signature is the value you get when you sign the header and payload together.

The final token is in the form of ...

These tokens are currently used in authorization and are faster and more compact than other authorization methods. These may be very useful in the future and their potential is very high.

Conclusion

In this article, we've seen the importance of JSON as a medium of data transfer between completely different systems, and why is it so convenient.

JSON is a universal medium and is not just specific to JavaScript. JSON is already used in NoSQL databases to store data in JSON format.

We also compared JSON and XML and saw why JSON is more efficient and faster than XML. In the future, we may develop even better ways of transmitting data.

The rate at which the internet is growing, efficient data transfer will be the highest priority. And JSON serves that function really well for now.

You can try new things with JSON and implement different data structures – it's open to innovation, and we should never stop experimenting.

Hope you liked my article. I have learned a lot by writing it, and your appreciation motivates me everyday, Do visit my internet home theabbie.github.io.