JSON Array Literals
This is a JSON string:
'{"name":"John", "age":30, "car":null}'
Within the JSON string, there's a JSON object described.
{"name":"John", "age":30, "car":null}
JSON objects are put in curly brackets {}.
JSON object literals consist of pairs of keys and values.
Keys and values are separated by a colon.
Keys have to be words, and whatever you put with them has to follow certain rules, like being in a format called JSON.
- string
- number
- object
- array
- boolean
- null
Each pair of key and value is split by a comma.
It's often mistaken to label a JSON object literal as 'a JSON object'.
JSON cannot be an object; it's a type of text format called a string.
The information is JSON only when it's in a string. When you change it to a JavaScript variable, it turns into a JavaScript object.
JavaScript Objects
You can make a JavaScript object from a JSON object literal.
Typically, you make a JavaScript object by analyzing a JSON string:
Accessing Object Values
You can get information from objects using a dot (.) like this:
You can get values from an object using square brackets ([]).
Looping an Object
You can go through properties of an object using a for-in loop.
In a for-in loop, use square brackets to get the values of a property.
<!DOCTYPE html>
<html>
<body>
<h2>Creating an Object from a JSON Literal</h2>
<p id="demo"></p>
<script>
const myObj = {
"name": "John",
"age": 30,
"car": null
};
document.getElementById("demo").innerHTML = myObj.name;
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<h2>Creating an Object Parsing JSON</h2>
<p id="demo"></p>
<script>
const myJSON = '{"name":"John", "age":30, "car":null}';
const myObj = JSON.parse(myJSON);
document.getElementById("demo").innerHTML = myObj.name;
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<h2>Access a JavaScript Object</h2>
<p id="demo"></p>
<script>
const myJSON = '{"name":"John", "age":30, "car":null}';
const myObj = JSON.parse(myJSON);
document.getElementById("demo").innerHTML = myObj.name;
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<h2>Access a JavaScript Object</h2>
<p id="demo"></p>
<script>
const myJSON = '{"name":"John", "age":30, "car":null}';
const myObj = JSON.parse(myJSON);
document.getElementById("demo").innerHTML = myObj["name"];
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<h2>Looping Object Properties</h2>
<p id="demo"></p>
<script>
const myJSON = '{"name":"John", "age":30, "car":null}';
const myObj = JSON.parse(myJSON);
let text = "";
for (const x in myObj) {
text += x + ", ";
}
document.getElementById("demo").innerHTML = text;
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<h2>Looping Object Properties</h2>
<p id="demo"></p>
<script>
const myJSON = '{"name":"John", "age":30, "car":null}';
const myObj = JSON.parse(myJSON);
let text = "";
for (const x in myObj) {
text += x + ", ";
}
document.getElementById("demo").innerHTML = text;
</script>
</body>
</html>