【问题标题】:JSON.parse and JSON.stringify [duplicate]JSON.parse 和 JSON.stringify [重复]
【发布时间】:2018-03-10 22:03:51
【问题描述】:

我正在尝试从 API 调用中获取对输出的响应,以便使用换行符等对其进行格式化。我尝试了解析和字符串化,但仍然只能将输出作为一行。

var HttpClient = function() {
this.get = function(url, callback) {
    var anHttpRequest = new XMLHttpRequest();
    anHttpRequest.onreadystatechange = function() { 
        if (anHttpRequest.readyState == 4 && anHttpRequest.status == 200)
            callback(anHttpRequest.responseText);
    }

    anHttpRequest.open( "GET", url, true );            
    anHttpRequest.send( null );

   }
}

var client = new HttpClient();
client.get("https://api.opendota.com/api/players/26202535/matches?limit=1", 
function(response) {

JSON.parse(response);
console.log(response);
document.getElementById("demo").innerHTML=response;

});

输出: [{"match_id":3469695808,"player_slot":3,"radiant_win":true,"duration":1237,"game_mode":22,"lobby_type":7,"hero_id":13,"start_time":1506540​​251, "version":20,"kills":11,"deaths":2,"assists":12,"skill":3,"leaver_status":0,"party_size":1}]

【问题讨论】:

    标签: javascript json api


    【解决方案1】:

    你需要一个 PRE 标签来保持良好的缩进(或添加 CSS white-space:pre 到你的目标标签),然后使用 JSON.stringify 的第三个参数来添加缩进

    var data = '[{"match_id":3469695808,"player_slot":3,"radiant_win":true,"duration":1237,"game_mode":22,"lobby_type":7,"hero_id":13,"start_time":1506540251,"version":20,"kills":11,"deaths":2,"assists":12,"skill":3,"leaver_status":0,"party_size":1}]'
    
    document.getElementById('demo').innerHTML = JSON.stringify(JSON.parse(data),null, 4);
    <pre id="demo"></pre>

    【讨论】:

    • 为什么需要stringify和parse?
    • original 是 JSON (a string) .... 为了美化它,你先解析然后 stringify :p
    猜你喜欢
    • 2014-09-11
    • 2014-07-06
    • 2019-12-09
    • 1970-01-01
    • 2015-01-25
    • 2022-01-25
    • 2015-06-29
    • 1970-01-01
    相关资源
    最近更新 更多