将括号添加到json ajax

将括号添加到json ajax

问题描述:

我正在使用一个名为(http://michaeleisenbraun.com/columns/)的插件将json转换为表。将括号添加到json ajax

我使用下面的代码:

<script> 
$.ajax({ 
     url:'/large-data.json', 
     dataType: 'json', 
     success: function(json) { 
      example2 = $('#example2').columns({ 
       data:json, 
      }); 
     } 
    }); 
</script> 

它运作良好,当JSON是在括号中,象下面这样:

[ 
    { 
    "id": 9998, 
    "isActive": false, 
    "balance": "$5", 
    "age": 38, 
    "eyeColor": "blue", 
    "name": "Lola Townsend", 
    "gender": "female", 
    "company": "...", 
    "email": "[email protected], 
    "phone": "..." 
    } 
] 

但是,如果JSON是不是括号也不行,如下所示:

{ 
    "id": 9998, 
    "isActive": false, 
    "balance": "$5", 
    "age": 38, 
    "eyeColor": "blue", 
    "name": "Lola Townsend", 
    "gender": "female", 
    "company": "...", 
    "email": "[email protected], 
    "phone": "..." 
    } 

json响应来自其他网站,所以我将无法控制它是否能够控制es /没有括号。

有没有一种方法可以确保json每次都返回括号,如果不是,那么括号会被添加?

我试过JSON.parse(),它没有工作。

第一个意思是它是一个数组对象,第二个只是一个对象。我现在并没有真正明白你想要做什么,但是如果它不是一个完整的对象,你可以简单地将对象分配到数组中。像这样:

if(!Arrays.isArray(yourObject)) { 
    var temp = [] ; 
    temp.push(yourObject); 
    yourObject= temp; 
} 

我还没有测试它,因为我不知道你想要做什么,但这是主要想法。

希望它有帮助!

  • 尼克

您可以使用正则表达式来检查代码是否与^\[|\n*\]$正确。如果字符串的第一个字符是[,并且最后一个是],则应该有2个匹配项。

您可以在这里测试:https://regex101.com/r/Cukwog/1