Lightning

Create a JSON string in JavaScript

Sometimes we might need to create a custom JSON string in a JavaScript section. Custom JSON string means, it can have any field which is or is not in any sObjects. There are multiple ways to create JSON string.

In this blog, We will see one such way which I feel its easy to understand and create.

var obj = new Object();
obj.label = 'Contact';
obj.name = 'Test Contact';
obj.Flag = true;
obj.type = 'icon';
var JSON_String_Result = JSON.stringify(obj);

console.log('-=-= Output: ' + JSON_String_Result);

Here we must first create a generic Object. Then different keys can be mentioned directly. Here, label, name, Flag, type all are keys and the right side part is its value. You can add your own key and its value. So then you print the same, you get following Output.


-=-= Output: {"label":"Contact","name":"Test Contact","Flag":true,"type":"icon"}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s