前端如何打印json格式字符串
时间: 2023-12-03 12:05:34 浏览: 244
可以通过使用JSON.stringify()方法将JSON对象转换为格式化的JSON字符串,并使用console.log()方法将其打印出来。例如:
```javascript
const myObj = { name: 'John', age: 30, city: 'New York' };
const jsonString = JSON.stringify(myObj, null, 2);
console.log(jsonString);
```
其中,第一个参数是要转换为JSON字符串的对象,第二个参数是一个可选的replacer函数,用于转换值或删除属性,第三个参数是一个可选的space参数,用于指定缩进的空格数。在上面的例子中,第二个参数为null,第三个参数为2,表示每个级别缩进两个空格。输出结果如下所示:
```
{
"name": "John",
"age": 30,
"city": "New York"
}
```
阅读全文
相关推荐
















