jQuery getJSON 到 console.log() 输出 json 结构

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20500836/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 01:11:54  来源:igfitidea点击:

getJSON to console.log() to output json structure

jqueryjson

提问by jeewan

I have the following code for getting json data:

我有以下用于获取 json 数据的代码:

$.getJSON( "assessments", function( assessments ) {
    console.log(assessments);
        });

I am perfectly getting all the data but the console has output as

我完美地获取了所有数据,但控制台的输出为

[Object, Object, Object, Object, Object, Object, Object, Object, Object]

I want to output the values in JSON structure like this:

我想像这样输出 JSON 结构中的值:

[
{
    "id": 1,
    "person": {
        "personId": "person1",
        "firstName": "Pactric"
    },
    "manager": {
        "managerId": "manager1"
    },
    "state": {
        "stateId": 1,
        "description": null
    },
    "comments": null
}
]

How to console.log() for this data to display exactly as above's JSON structure? I am using $.getJSON NOT $.ajax for this application.

如何使用 console.log() 来让这个数据完全按照上面的 JSON 结构显示?我在这个应用程序中使用 $.getJSON NOT $.ajax。

回答by Anand Jha

try with

尝试

console.log(JSON.stringify(assessments));

回答by adeneo

Stringify the JSON with indentation like so :

像这样使用缩进对 JSON 进行字符串化:

$.getJSON( "assessments", function( assessments ) {
    console.log(JSON.stringify(assessments, undefined, 2))
});

JSON.stringify(value[, replacer [, space]])where space is the indent. MDN

JSON.stringify(value[, replacer [, space]])其中空格是缩进。MDN