Javascript: JSON tutorial

JSON is a notation derived from Javascript. It is open and human-readable, therefore commonly used with other technologies (see this post, showing how to use it with Java/Android). Here are some basic operations with JSON in JavaScript:

1. Create simple JSON

var jsonMessage = {
    "message": "statusUpdate",
    "object": "object-1"
}

This is how result will look like:

{
	"message":"statusUpdate",
	"object":"object-1",
}

now you have a JSON variable made as simple String. It would be more useful with parameters, so see the next point.

2. Create parametrized JSON message

var changeType = "statusUpdate";
var objectId = "object-1";

var jsonMessage = {
	"message": changeType,
	"object": objectId
}

The result will look exactly the same as in point 1.

Here the JSON message is created with two variables, which is the real life example, since values are often dynamic.

3. Adding new key to existing JSON

When we have JSON message that has to be extended (new key added) it is as simple as follows:

var changeType = "statusUpdate";
var objectId = "object-1";

var jsonMessage = {
        "message": changeType,
	"object": objectId
}

jsonMessage.info = "More info...";

The resulting JSON will look like below:

{
	"message":"statusUpdate",
	"object":"object-1",
	"info":"More info..."
}

4. Create and add JSON Array to JSON message
JSON Array is created from Javascript array, so to create id just create new variable and add it to JSON, as a new element (like in point 3):

var changeType = "statusUpdate";
var objectId = "object-1";

var jsonMessage = {
	"message": changeType,
	"object": objectId
}

var jsonArray = ["one", "two", "three"];
jsonMessage.myArray = jsonArray;

And this will be the result:

{
	"message":"statusUpdate",
	"object":"object-1",
	"myArray":[
		"one",
		"two",
		"three"
	]
}

5. Change element in JSON Array
This is as simple as:

var changeType = "statusUpdate";
var objectId = "object-1";

var jsonMessage = {
	"message": changeType,
	"object": objectId
}

var jsonArray = ["one", "two", "three"];
jsonMessage.myArray = jsonArray;
jsonMessage.myArray[1] = "changed";

So that we now have an output (compare it to output myArray in point 4):

{
	"message":"statusUpdate",
	"object":"object-1",
	"myArray":[
		"one",
		"changed",
		"three"
	]
}

Did I help you?
I manage this blog and share my knowledge for free sacrificing my time. If you appreciate it and find this information helpful, please consider making a donation in order to keep this page alive and improve quality

Donate Button with Credit Cards

Thank You!

Give Your feedback: