What are the methods to convert JSON to a string?
There are several ways to convert JSON to a string.
- Utilize the JSON.stringify() method:
const json = { "name": "John", "age": 30 };
const jsonString = JSON.stringify(json);
console.log(jsonString);
- By using the second parameter of the JSON.stringify() method, you can format the conversion result.
const json = { "name": "John", "age": 30 };
const jsonString = JSON.stringify(json, null, 2); // 使用两个空格进行缩进
console.log(jsonString);
- With the second parameter of the JSON.stringify() method, you can select the properties you want to serialize.
const json = { "name": "John", "age": 30, "city": "New York" };
const jsonString = JSON.stringify(json, ["name", "age"]);
console.log(jsonString);
- The second parameter of the JSON.stringify() method allows you to pass a function to customize the serialization of property values.
const json = { "name": "John", "age": 30, "city": "New York" };
const jsonString = JSON.stringify(json, (key, value) => {
if (key === "city") {
return undefined; // 不序列化 city 属性
}
return value;
});
console.log(jsonString);
- You can specify an indent character using the third parameter of the JSON.stringify() method.
const json = { "name": "John", "age": 30 };
const jsonString = JSON.stringify(json, null, "\t"); // 使用制表符进行缩进
console.log(jsonString);
The methods listed above are commonly used for converting JSON to strings, choose the one that suits your needs.