Summary of Intro to JSON & Beginner's Guide to JSON:
JSON (JavaScript Object Notation): a lightweight data-interchange format and an ideal language for data-interchange since it is..
It is one of the most popular data-interchange standards for a good reason. It is not, however, the be-all and end-all solution for all situations (e.g. other standards such as YAML are more appropriate for stuff like config files.)
JSON is built on two structures:
These are universal data structures supported by virtually all modern programming languages in one form or another. It makes sense that a data format that is interchangeable with programming languages also be based on these structures.
In JSON, they take on the form of an object, which is an unordered set of name/value pairs that beings with {left brace and ends with }right brace. Each name is followed by :colon and the name/value pairs are separated by ,comma.
const message = {
sender: "김코딩",
receiver: "박해커",
message: "해커야 오늘 저녁 같이 먹을래?",
createdAt: "2021-01-12 10:10:10"
}
If you want to send an object (like above) to another program via the network, the sender and receiver of the message needs to be using the same program, or the message needs to be a universal format (e.g. string) that can be generally read anywhere (what is referred to as transferable condition).
An object's contents cannot be stringified with type conversion/coercion (for instance, methods such as message.toString()
or type conversion such as String(message)
will only return [object Object]
.
(Sidebar: check this out for a deeper explanation of [object Object]. TLDR: Every object has a toString()
method that is automatically called when the object is to be represented as a text value or when an object is referred to in a manner in which a string is expected. Object.prototype.toString
is a method that detects the class of an object and tells you what it is (as in, it prints out the name of the class you passed into toString
.)
Utilizing JSON provides a simple solution to this problem: you can transform the object into a JSON object to send it over a network, and likewise transform a JSON object to an object when you fetch or receive something over a network. It is
JSON.stringify
: converts object to JSON (serializing) JSON.parse
: converts JSON into object (de-serializing)JS Object | JSON | |
---|---|---|
Key | Does not need double quotes{ key : "property" } | Must be wrapped in double quotes '{"key":"property"}' |
String value | Can be wrapped in single quotes{ "key" : 'property' } | Must be wrapped in double quotes'{"key":"property"}' |
Space Between Key & Value | Is allowed {"key" : 'property'} | Not allowed '{"key":"property"}' |
Space Between Key-Value Pairs | Is allowed{ "key":'property', num:1 } | Not allowed '{"key":"property","num":1}' |
obj === null
(typeof null is equal to 'object') //REFERENCE CODE
function stringifyJSON(obj) {
if (obj === null) {
return "null";
}
if (typeof obj === "number" || typeof obj === "boolean") {
return String(obj);
}
if (typeof obj === "string") {
return `"${obj}"`;
}
//if an object is an array
if (Array.isArray(obj)) {
const result = [];
obj.forEach(function (element) {
result.push(stringifyJSON(element))
})
return `[${result}]`;
}
//if it's an object (array also is an 'object' but was already filtered above
if (typeof obj === "object") {
let result = "";
for (let key in obj) {
if (obj[key] === undefined || typeof obj[key] === "function") {
result = String(result);
} else {
result = result + `${stringifyJSON(key)}:${stringifyJSON(obj[key])},`;
}
}
result = result.substr(0, result.length - 1);
return `{${result}}`;
}
};
if (typeof window === "undefined") {
module.exports = stringifyJSON;
//SUB-OPTIMAL CODE TO LEARN WHAT ***NOT*** TO DO
function stringifyJSON(obj) {
if (typeof obj === 'string'){
return `"${obj}"`; //add double quotes for string
}
if(Array.isArray(obj)){
//if (!obj.length) return `[]`; -> not necessary!
let result = obj.map(el => stringifyJSON(el)); //map result needs to be contained somewhere! Does not change the original array
return `[${result}]`;
}
if(typeof obj === 'object' && obj !== null){
// if (!Object.keys(obj).length) return `{}`; -> not necessary!
const keys = [];
const values = [];
let result = '';
//four for loops! suboptimal. can be done within one for loop
for (let key in obj){ //filter out the functions and undefined
if(typeof obj[key] === 'function' || typeof obj[key] === 'undefined')
return `{}`;
}
for (let key of Object.keys(obj)) {keys.push(stringifyJSON(key));}
for (let val of Object.values(obj)) {values.push(stringifyJSON(val));}
for (let i = 0; i < keys.length; i++){
result += keys[i] + ":" + values[i] + ',';
}
result = result.slice(0, -1); //cut off the last comma
return `{${result}}`;
}else{
//number, boolean, null
return `${obj}`;
}
};
Introducing JSON
A beginner’s guide to JSON, the data format for the internet
What Is [object Object] in JavaScript: Object.prototype.toString
<For further Study>