乐闻世界logo
搜索文章和话题

How to Convert array to JSON in javascript

1个答案

1

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:

javascript
let 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:

javascript
let 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.

2024年6月29日 12:07 回复

你的答案