json对象转换为json字符串
时间: 2023-08-17 16:31:46 浏览: 62
可以使用JSON.stringify()方法将JSON对象转换为JSON字符串,示例如下:
```javascript
let jsonObj = { "name": "John", "age": 30, "city": "New York" };
let jsonString = JSON.stringify(jsonObj);
console.log(jsonString); // 输出: {"name":"John","age":30,"city":"New York"}
```
注意,JSON.stringify()方法还可以接受第二个参数,用于控制输出的格式。例如,可以将输出的JSON字符串缩进两个空格:
```javascript
let jsonObj = { "name": "John", "age": 30, "city": "New York" };
let jsonString = JSON.stringify(jsonObj, null, 2); // 第二个参数为null,第三个参数为2
console.log(jsonString);
// 输出:
// {
// "name": "John",
// "age": 30,
// "city": "New York"
// }
```