Tip to create JSON string.

If you are going to create a JSON string dynamically then this TIP may be helpful for you. In this i have convert a JavaScript array into JSON string by two ways.

JSON

Method 1 :- 

    <script type="text/javascript">
        var arrCharacters = ['A', 'B', 'C', 'D', 'E', 'F'];

        var json = '{';
        for (i = 0; i < arrCharacters.length; i++) {
            if (json != '{') {
                json += ',';
            }

            json += '"Char[' + i + ']":"' + arrCharacters[i] + '"';
        }
        json += '}';
        console.log(json);
        //OUTPUT: {"Char[0]":"A","Char[1]":"B","Char[2]":"C","Char[3]":"D","Char[4]":"E","Char[5]":"F"}        
    </script

Method 2:-

    <script type="text/javascript">

        var arrCharacters = ['A', 'B', 'C', 'D', 'E', 'F'];

        var tempObject = {};
        for (i = 0; i < arrCharacters.length; i++) {
            tempObject['Char[' + i+']'] = arrCharacters[i];
        }
        var jsonByObject = JSON.stringify(tempObject,'','\t');

        console.log(jsonByObject);        
	//OUTPUT: {"Char[0]":"A","Char[1]":"B","Char[2]":"C","Char[3]":"D","Char[4]":"E","Char[5]":"F"}
    </script>

Programming is Easy…

Advertisements

3 thoughts on “Tip to create JSON string.

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 )

Google+ photo

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

Connecting to %s