JSON with Javascript and Jquery

JSJavascript has grown  from a way to add interactivity on your page , to a language that lets you perform tasks that once belonged to servers.JSON provides for an easy way to create and store data structures within JavaScript. JSON stands for JavaScript Object Notation…it’s called that because storing data with JSON creates a JavaScript object. The JavaScript object can be easily parsed and manipulated with JavaScript.

First, we create a variable to hold our data, and then we use JSON to define our object. Our sample object above is a simple as it gets. Just an item called firstName and it’s value Sam. When using strings with JSON, you should use them with quotations as above. If you use numbers, then you don’t have to use quotations.

<script> var data = { “Firstname”: “Sam” }; alert(data.Firstname); </script>

Let’s put data inside an HTML element.

<script>
var data = {
"Firstname": "Sam",
"Lastname": "Legend",
"Age": "34"
};

 document.getElementById("placeholder").innerHTML = data.Firstname + " " + data.Lastname + " " + data.Age;
</script>
  • Every object in json is stored with curly braces {}, an array is stored with brackets[].

  • So in order to organize our data, we created an object called users, which held an array (using brackets).

  • That object had a couple of other objects…each stored like before with curly braces {}.

  • Each element in that object was separated by commas.

<html>
<head>
<meta charset="utf-8" />
<title>JSON Data</title>
</head>
<body>
 <div id="placeholder"> </div>
</body>
</html>
<script>
var data = {
"users": [
{
"Firstname": "Sam",
"Lastname": "Legend",
"Age": "34"
},
{
"Firstname": "John",
"Lastname": "Watson",
"Age": "22"
}
]
};
 document.getElementById("placeholder").innerHTML = data.users[0].Firstname + " " + data.users[0].Lastname + " " + data.users[0].Age;
</script>


Leave a Comment

Your email address will not be published.