JSON Object Literals
Here is a JSON string:
'{"name":"John", "age":30, "car":null}'
Within the JSON string, there exists a JSON object literal.
{"name":"John", "age":30, "car":null}
JSON object literals are embraced by curly braces {} in code.
JSON object literals consist of pairs of keys and values.
In HTML, we separate keys and values using a colon.
Make sure that the keys are written as strings, and the values are valid JSON data types.
- string
- number
- object
- array
- boolean
- null
Every pair of key and value is divided by a comma.
People often confuse a JSON object literal with just a "JSON object."
JSON cannot be treated as an object. It's a format for strings.
JSON data is just a string until it's in a special format. When you change it into a JavaScript variable, it turns into a JavaScript object.
JavaScript Objects
You can make a JavaScript object using a JSON object literal.
Typically, you make a JavaScript object by analyzing a JSON string.
Accessing Object Values
You can retrieve values from an object by using a dot (.) notation.
You can retrieve values from an object by using square bracket ([]) notation.
Looping an Object
You can go through the properties of an object using a for-in loop.
In a for-in loop, use bracket notation to access the property values:
<!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 JavaScript Object Values</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 += myObj[x] + ", ";
}
document.getElementById("demo").innerHTML = text;
</script>
</body>
</html>