JavaScript Function to Convert Array to JSON

JavaScript Function to Convert Array to JSON

JSON is a lightweight data exchange platform when Array is used to store small chunk of data during development. Sometimes during development we required to convert an array to JSON. Let’s talk about a single dimension array. In the below example I am converting a single dimension Array to JSON.

In the below demo app I have an array tempArray which contains 5 elements. To convert this array into formatted JSON I created a function ArrayToJSON(). Which accepts array as a parameter. In side the function I have a string variable json. Which holds the initial value as JSON attribute as json = ‘{“attrs”:[‘;. After this I am running a for loop which doing string concatenation for id & value pair to my json string variable. Finally using json += ‘]}’; I am ending the JSON string.

Convert Array to JSON

/* Array Declaration */
var tempArray = [10, 12, 14, 16, 18];
/* Function to Convert an Array into formatted JSON */
function ArrayToJSON(array) {
var json = null;
/* Adding attributes to beginning JSON String */
json = '{"attrs":[';
/* Using String Concatenation building JSON key value pairs */
for (var i=0; i<array.length; i++) {
json += '{"' + 'id' + '":"' + array[i] + '"},';
/* Removing the last Comma from JSON string */
json = json.substring(0, json.length-1);
/* Closing JSON String */
json += ']}';
/* Returning the formatted JSON */
return json;
var res = ArrayToJSON(tempArray);

/* Output JSON */
/* {“attrs”:[{“id”:”10″},{“id”:”12″},{“id”:”14″},{“id”:”16″},{“id”:”18″}]} */