In JavaScript, converting an array to a JSON-formatted string is straightforward. This can be achieved by using the stringify method of the global JSON object. The JSON.stringify() method accepts an array (or any JavaScript object) and returns a JSON-formatted string.
Here is a specific example to illustrate this process:
Assume we have an array with the following content:
javascriptlet myArray = [ { name: "Tom", age: 28 }, { name: "Jerry", age: 22 }, { name: "Mickey", age: 35 } ];
This array contains three objects, each with name and age properties. Now, we want to convert this array into a JSON-formatted string.
We can use the JSON.stringify() method:
javascriptlet jsonArray = JSON.stringify(myArray); console.log(jsonArray);
After running the above code, the output printed in the console will be:
json["{\"name\":\"Tom\",\"age\":28}","{\"name\":\"Jerry\",\"age\":22}","{\"name\":\"Mickey\",\"age\":35}"]
Thus, we have successfully converted a JavaScript array into a JSON-formatted string, which can be used for network transmission, file storage, and various other scenarios.