USING JSON TO REPRESENT OBJECTS
In 1999, JSON (JavaScript Object Notation)—a simple way to represent JavaScript objects as
strings—was introduced as an alternative to XML as a data-exchange technique. JSON has gained
acclaim due to its simple format, making objects easy to read, create and parse. Each JSON object
is represented as a list of property names and values contained in curly braces, in the following
format:
{ propertyName1 : value1, propertyName2 : value2 }
Arrays are represented in JSON with square brackets in the following format:
[ value1, value2, value3 ]
Each value can be a string, a number, a JSON object, true, false or null. To appreciate the simplicity
of JSON data, examine this representation of an array of address-book entries:
[ { first: 'Cheryl', last: 'Black' },
{ first: 'James', last: 'Blue' },
{ first: 'Mike', last: 'Brown' },
{ first: 'Meg', last: 'Gold' } ]
JSON provides a straightforward way to manipulate objects in JavaScript, and many other
programming languages now support this format. In addition to simplifying object creation, JSON
allows programs to extract data easily and to efficiently transmit data across the Internet.
dard text-based format for representing structured data based
on JavaScript object syntax.
Example 1 :
// JSON object
const data = {
"name": "John",
"age": 22,
"hobby": {
"reading" : true,
"gaming" : false,
"sport" : "football“
},
"class" : ["JavaScript", "HTML", "CSS"]}
[Link]([Link]);
[Link]([Link]);
[Link]([Link]);
[Link]([Link][1]);
<!DOCTYPE html>
<html>
<body>
<h2>Access a JavaScript object</h2>
<p id="demo"></p>
<script>
const myObj = {name:"John", age:30, city:"New York",
hobby:{reading:"true",gaming:"false"},class:["Javascript","HTML","CSS"]};
[Link]("demo").innerHTML = myObj["class"][1];
</script>
</body>
</html>
OUTPUT:
EXAMPLE 2:
<!DOCTYPE html>
<html>
<body>
<h2>Access a JavaScript object</h2>
<p id="demo"></p>
<script>
const myObj = {name:"John", age:30, city:"New York"};
[Link]("demo").innerHTML = myObj["name"];
</script>
</body>
</html>
Output:
Access a JavaScript Object
John
Keys must be strings, and values must be a valid JSON data type:
string
number
object
array
boolean
null
rmat. When it is converted to a JavaScript variable,
it becomes a JavaScript object.
EXAMPLE 3:
<!DOCTYPE html>
<html>
<body>
<h2>Creating an Object from a JSON String</h2>
<p id="demo"></p>
<script>
const txt = '{"name":"John", "age":30, "city":"New York"}'
const obj = [Link](txt);
[Link]("demo").innerHTML = [Link] + ", " + [Link];
</script>
</body>
</html>
OUTPUT:
Creating an Object from a JSON String
30