JSON.parse和JSON.stringify

时间:2017-09-29 03:29:05

标签: javascript json api

我试图从API调用到输出的响应,以便使用换行符等格式化它。我尝试了解析和字符串化,仍然只将输出作为一行。 var HttpClient = function(){ this.get = function(url,callback){     var anHttpRequest = new XMLHttpRequest();     anHttpRequest.onreadystatechange = function(){         if(anHttpRequest.readyState == 4&& anHttpRequest.status == 200)             回调(anHttpRequest.responseText);     }     anHttpRequest.open(" GET",url,true);     anHttpRequest.send(null);    } } var client = new HttpClient(); client.get(" HTTPS://api.opendota.com/api/players/26202535/matches极限= 1&#34 ;,? function(response){ JSON.parse(响应); 的console.log(响应); 的document.getElementById("演示&#34)。innerHTML的响应=; }); 输出: [{" match_id":3469695808," player_slot":3," radiant_win":真,"持续时间":1237," game_mode":22," lobby_type":7," hero_id":13," START_TIME":1506540​​251,"版本":20 "杀死":11,"死亡":2"协助":12,"技术人员":3," leaver_status& #34;:0," party_size":1}]

1 个答案:

答案 0 :(得分: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>
&#13;
&#13;
&#13;