如何解析非Json数据hemera

时间:2017-08-14 06:13:21

标签: javascript json parsing

我是Json和JavaScript的新手。目前我有一个url,它返回一个JSON响应。但问题是,它的格式不正确。请参阅下面的回复

var pd={ player: 
   { id: 363609002,
     game: 'bf4',
     plat: 'pc',
     name: 'm4jes',
     tag: 'BPt',
     dateCheck: 1487204427149,
     dateUpdate: 1474581052618,
     dateCreate: 1384980182606,
     dateStreak: 1474581052618,
     lastDay: '20160715',
     country: '',
     countryName: null,
     rank: 
      { nr: 121,
        imgLarge: 'bf4/ranks/r121.png',
        img: 'r121',
        name: 'Major General II',
        needed: 16110000,
        next: 
         { nr: 122,
           imgLarge: 'bf4/ranks/r122.png',
           img: 'r122',
           name: 'Major General III',
           needed: 16750000,
           curr: 16720600,
           relNeeded: 640000,
           relCurr: 610600,
           relProg: 95.40625 } },
     score: 16724643,
     timePlayed: 1476950,
     uId: '2832665149467333131',
     uName: 'm4jes',
     uGava: '721951facb53ed5632e196932fb6c72e',
     udCreate: 1319759388000,
     privacy: 'friends',
     blPlayer: 'http://battlelog.battlefield.com/bf4/soldier/m4jes/stats/363609002/pc/',
     blUser: 'http://battlelog.battlefield.com/bf4/user/m4jes/',
     editable: false,
     viewable: true,
     adminable: false,
     linked: false },}

从上面的反应我必须得到输出:

{
  game: 'bf4',
  plat: 'pc',
  name: 'm4jes',
  tag: 'BPt',
  score: 16724643,
  timePlayed: 1476950
}

通过哪种方法我可以在Javascript中获得所需的

1 个答案:

答案 0 :(得分:1)

首先,URL不返回JSON响应,而是返回JS对象文字。区别在于here

你必须从网址获取字符串。您可以使用jQuery方法get()

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
var jqxhr = $.get( "https://api.bf4stats.com/api/playerInfo?plat=pc&name=m4jes&output=js", function() {
  //Insert the rest of the code here
});
</script>

然后,jqxhr.responseText是与我们想要的对象相对应的字符串。使用eval,我们将字符串转换为对象:

pd = eval(jqxhr.responseText);

所以这里我们有一个对象文字,其中包含所有对名称/值。您可以使用点表示法访问所需的值。例如,如果你想获得游戏名称,可以写下:

pd.player.game

所以这导致:

var myNewObject = {
   game: pd.player.game,
   plat: pd.player.plat,
   name: pd.player.name,
   tag: pd.player.tag,
   score: pd.player.score,
   timePlayed: pd.player.timePlayed,
 }

然后,您必须使用JSON.stringify() method将此JS对象文字转换为JSON:

console.log(JSON.stringify(myNewObject, null, '\t'));

它返回你想要的东西:

    {
        "game": "bf4",
        "plat": "pc",
        "name": "m4jes",
        "tag": "BPt",
        "score": 16724643,
        "timePlayed": 1476950
    }

所以这是完整的代码:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
var jqxhr = $.get( "https://api.bf4stats.com/api/playerInfo?plat=pc&name=m4jes&output=js", function() {
  pd = eval(jqxhr.responseText);

  var myNewObject = {
   game: pd.player.game,
   plat: pd.player.plat,
   name: pd.player.name,
   tag: pd.player.tag,
   score: pd.player.score,
   timePlayed: pd.player.timePlayed,
 }

 console.log(JSON.stringify(myNewObject, null, '\t'));
});
</script>